



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 						_lowerCAmelCase    (					__lowerCamelCase :  str		,						__lowerCamelCase :  Any  ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE							:     List[str]							=						nn.functional.normalize(__lowerCamelCase  )
 __SCREAMING_SNAKE_CASE							:     int							=						nn.functional.normalize(__lowerCamelCase  )
 return torch.mm(__lowerCamelCase		,						normalized_text_embeds.t()  )






class    _SCREAMING_SNAKE_CASE						(UpperCamelCase			):
     lowerCAmelCase       =      CLIPConfig

     lowerCAmelCase       =      ["""CLIPEncoderLayer"""]





     def __init__(							self			:				int  ,	UpperCamelCase			:				CLIPConfig					)->Optional[Any]:
      super().__init__(UpperCamelCase					)

      __SCREAMING_SNAKE_CASE							:     int							=						CLIPVisionModel(config.vision_config					)
      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						nn.Linear(config.vision_config.hidden_size  ,	config.projection_dim  ,	bias=UpperCamelCase					)

      __SCREAMING_SNAKE_CASE							:     str							=						nn.Parameter(torch.ones(1_7  ,	config.projection_dim					)  ,	requires_grad=UpperCamelCase					)
      __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						nn.Parameter(torch.ones(3  ,	config.projection_dim					)  ,	requires_grad=UpperCamelCase					)

      __SCREAMING_SNAKE_CASE							:     List[Any]							=						nn.Parameter(torch.ones(1_7					)  ,	requires_grad=UpperCamelCase					)
      __SCREAMING_SNAKE_CASE							:     Dict							=						nn.Parameter(torch.ones(3					)  ,	requires_grad=UpperCamelCase					)





     @torch.no_grad()
     def 						__snake_case     (							self			:				List[Any]  ,	UpperCamelCase			:				Any  ,	UpperCamelCase			:				str					)->str:
      __SCREAMING_SNAKE_CASE							:     int							=						self.vision_model(UpperCamelCase					)[1]  # pooled_output
      __SCREAMING_SNAKE_CASE							:     List[Any]							=						self.visual_projection(UpperCamelCase					)

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

      __SCREAMING_SNAKE_CASE							:     Dict							=						[]
      __SCREAMING_SNAKE_CASE							:     List[str]							=						image_embeds.shape[0]
      for i in range(UpperCamelCase					):
       __SCREAMING_SNAKE_CASE							:     List[str]							=						{"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
       __SCREAMING_SNAKE_CASE							:     List[Any]							=						0.0

       for concept_idx in range(len(special_cos_dist[0]					)					):
        __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						special_cos_dist[i][concept_idx]
        __SCREAMING_SNAKE_CASE							:     Optional[int]							=						self.special_care_embeds_weights[concept_idx].item()
        __SCREAMING_SNAKE_CASE							:     Dict							=						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]}					)
         __SCREAMING_SNAKE_CASE							:     Dict							=						0.0_1

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

       result.append(UpperCamelCase					)

      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						[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]					):
         __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						torch.zeros_like(images[idx]					)  # black image
        else:
         __SCREAMING_SNAKE_CASE							:     Tuple							=						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 						__snake_case     (							self			:				Any  ,	UpperCamelCase			:				torch.FloatTensor  ,	UpperCamelCase			:				torch.FloatTensor					)->int:
      __SCREAMING_SNAKE_CASE							:     Dict							=						self.vision_model(UpperCamelCase					)[1]  # pooled_output
      __SCREAMING_SNAKE_CASE							:     str							=						self.visual_projection(UpperCamelCase					)

      __SCREAMING_SNAKE_CASE							:     Dict							=						cosine_distance(UpperCamelCase  ,	self.special_care_embeds					)
      __SCREAMING_SNAKE_CASE							:     str							=						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
      __SCREAMING_SNAKE_CASE							:     List[Any]							=						0.0

      __SCREAMING_SNAKE_CASE							:     Tuple							=						special_cos_dist - self.special_care_embeds_weights + adjustment
      # special_scores = special_scores.round(decimals=3)
      __SCREAMING_SNAKE_CASE							:     Tuple							=						torch.any(special_scores > 0  ,	dim=1					)
      __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						special_care * 0.0_1
      __SCREAMING_SNAKE_CASE							:     Optional[int]							=						special_adjustment.unsqueeze(1					).expand(-1  ,	cos_dist.shape[1]					)

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

      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						0.0  # black image

      return images, has_nsfw_concepts











from __future__ import annotations

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

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

class    _SCREAMING_SNAKE_CASE						(Generic[T]			):





     def __init__(							self			:				List[Any]  ,	UpperCamelCase			:				T					)->None:
      __SCREAMING_SNAKE_CASE							:     T							=						value
      __SCREAMING_SNAKE_CASE							:     SkewNode[T] | None							=						None
      __SCREAMING_SNAKE_CASE							:     SkewNode[T] | None							=						None





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






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

      if not roota:
       return roota

      if roota.value > roota.value:
       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE							:     List[Any]							=						roota, roota

      __SCREAMING_SNAKE_CASE							:     int							=						roota
      __SCREAMING_SNAKE_CASE							:     str							=						roota.right
      __SCREAMING_SNAKE_CASE							:     int							=						roota.left
      __SCREAMING_SNAKE_CASE							:     Optional[int]							=						SkewNode.merge(UpperCamelCase  ,	UpperCamelCase					)

      return result






class    _SCREAMING_SNAKE_CASE						(Generic[T]			):





     def __init__(							self			:				str  ,	UpperCamelCase			:				Iterable[T] | None = ()					)->None:
      __SCREAMING_SNAKE_CASE							:     SkewNode[T] | None							=						None
      if data:
       for item in data:
        self.insert(UpperCamelCase					)





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





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

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

      return iter(UpperCamelCase					)





     def 						__snake_case     (							self			:				List[Any]  ,	UpperCamelCase			:				T					)->None:
      __SCREAMING_SNAKE_CASE							:     str							=						SkewNode.merge(self._root  ,	SkewNode(UpperCamelCase					)					)





     def 						__snake_case     (							self			:				List[Any]					)->T | None:
      __SCREAMING_SNAKE_CASE							:     Any							=						self.top()
      __SCREAMING_SNAKE_CASE							:     List[Any]							=						(
          SkewNode.merge(self._root.left  ,	self._root.right					) if self._root else None
      )

      return result





     def 						__snake_case     (							self			:				Optional[int]					)->T:
      if not self._root:
       raise IndexError("Can't get top element for the empty heap."					)
      return self._root.value






     def 						__snake_case     (							self			:				Dict					)->None:
      __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						None


if __name__ == "__main__":
      import doctest

      doctest.testmod()






