






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

from ...utils import logging


__UpperCAmelCase      =				logging.get_logger(__name__)





def 						A_					(						lowercase_	,  lowercase_			)				->Union[str, Any]:







 """simple docstring"""

 SCREAMING_SNAKE_CASE				    =		nn.functional.normalize(lowercase_			)
 SCREAMING_SNAKE_CASE				    =		nn.functional.normalize(lowercase_			)
 return torch.mm(lowercase_	,  normalized_text_embeds.t()			)
class 	a_(		lowerCAmelCase__	):



     """simple docstring"""



     __snake_case		:				List[str]  					=CLIPConfig

     __snake_case		:				Tuple  					=["CLIPEncoderLayer"]





     def __init__(		self					:	List[str]  ,  lowerCAmelCase__					:	CLIPConfig)							->	Any:

      """simple docstring"""
      super().__init__(_UpperCAmelCase)

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

      SCREAMING_SNAKE_CASE				    =		nn.Parameter(torch.ones(1_7  ,  config.projection_dim)  ,  requires_grad=_UpperCAmelCase)
      SCREAMING_SNAKE_CASE				    =		nn.Parameter(torch.ones(3  ,  config.projection_dim)  ,  requires_grad=_UpperCAmelCase)

      SCREAMING_SNAKE_CASE				    =		nn.Parameter(torch.ones(1_7)  ,  requires_grad=_UpperCAmelCase)
      SCREAMING_SNAKE_CASE				    =		nn.Parameter(torch.ones(3)  ,  requires_grad=_UpperCAmelCase)





     @torch.no_grad()
     def     __UpperCamelCase						(		self					:	Any  ,  lowerCAmelCase__					:	str  ,  lowerCAmelCase__					:	List[str])							->	str:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		self.vision_model(_UpperCAmelCase)[1]  # pooled_output
      SCREAMING_SNAKE_CASE				    =		self.visual_projection(_UpperCAmelCase)

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

      SCREAMING_SNAKE_CASE				    =		[]
      SCREAMING_SNAKE_CASE				    =		image_embeds.shape[0]
      for i in range(_UpperCAmelCase):
       SCREAMING_SNAKE_CASE				    =		{'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				    =		0.0

       for concept_idx in range(len(special_cos_dist[0])):
        SCREAMING_SNAKE_CASE				    =		special_cos_dist[i][concept_idx]
        SCREAMING_SNAKE_CASE				    =		self.special_care_embeds_weights[concept_idx].item()
        SCREAMING_SNAKE_CASE				    =		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				    =		0.01

       for concept_idx in range(len(cos_dist[0])):
        SCREAMING_SNAKE_CASE				    =		cos_dist[i][concept_idx]
        SCREAMING_SNAKE_CASE				    =		self.concept_embeds_weights[concept_idx].item()
        SCREAMING_SNAKE_CASE				    =		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				    =		[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				    =		torch.zeros_like(images[idx])  # black image
        else:
         SCREAMING_SNAKE_CASE				    =		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					:	str  ,  lowerCAmelCase__					:	torch.FloatTensor  ,  lowerCAmelCase__					:	torch.FloatTensor)							->	Tuple:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		self.vision_model(_UpperCAmelCase)[1]  # pooled_output
      SCREAMING_SNAKE_CASE				    =		self.visual_projection(_UpperCAmelCase)

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

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

      SCREAMING_SNAKE_CASE				    =		(cos_dist - self.concept_embeds_weights) + special_adjustment
      # concept_scores = concept_scores.round(decimals=3)
      SCREAMING_SNAKE_CASE				    =		torch.any(concept_scores > 0  ,  dim=1)

      SCREAMING_SNAKE_CASE				    =		0.0  # black image

      return images, has_nsfw_concepts






def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: Union[str, Any]       ,				SCREAMING_SNAKE_CASE			: Any     )	->		Tuple:
				# "Simpson Rule"
				# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
				__lowercase								=   (boundary[1] - boundary[0]) / steps
				__lowercase								=   boundary[0]
				__lowercase								=   boundary[1]
				__lowercase								=   make_points(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE     )
				__lowercase								=   0.0
				y += (h / 3.0) * f(SCREAMING_SNAKE_CASE     )
				__lowercase								=   2
				for i in x_i:
								y += (h / 3) * (4 - 2 * (cnt % 2)) * f(SCREAMING_SNAKE_CASE     )
								cnt += 1
				y += (h / 3.0) * f(SCREAMING_SNAKE_CASE     )
				return y




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: List[Any]       ,				SCREAMING_SNAKE_CASE			: Dict       ,				SCREAMING_SNAKE_CASE			: int     )	->		Any:
				__lowercase								=   a + h
				while x < (b - h):
								yield x
								__lowercase								=   x + h




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: Any     )	->		List[Any]:  # enter your function here
				__lowercase								=   (x - 0) * (x - 0)
				return y




def 				__SCREAMING_SNAKE_CASE  (						)	->		List[str]:
				__lowercase								=   0.0  # Lower bound of integration
				__lowercase								=   1.0  # Upper bound of integration
				__lowercase								=   10.0  # define number of steps or resolution
				__lowercase								=   [a, b]  # define boundary of integration
				__lowercase								=   method_a(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE     )
				print(F"""y = {y}"""     )


if __name__ == "__main__":
							main()





