






"""simple docstring"""


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

from ...utils import logging


_UpperCamelCase :    Optional[Any]      =			logging.get_logger(__name__)




def 					a			(  UpperCamelCase_				:					Any  ,						UpperCamelCase_				:					Dict		)	->		Dict:
 __A						:							List[str]      =						nn.functional.normalize(UpperCamelCase_		)
 __A						:							str      =						nn.functional.normalize(UpperCamelCase_		)
 return torch.mm(UpperCamelCase_  ,						normalized_text_embeds.t()		)






class __a ( snake_case_					):
  __lowercase     :     List[str]       						=       CLIPConfig

  __lowercase     :     Union[str, Any]       						=       ['CLIPEncoderLayer']



  def __init__(self	:		Any					,      lowercase_	:		CLIPConfig )		->				List[str]:
   super().__init__(lowercase_ )

   __A						:							Optional[int]      =						CLIPVisionModel(config.vision_config )
   __A						:							Dict      =						nn.Linear(config.vision_config.hidden_size					,      config.projection_dim					,      bias=lowercase_ )

   __A						:							Any      =						nn.Parameter(torch.ones(17					,      config.projection_dim )					,      requires_grad=lowercase_ )
   __A						:							List[Any]      =						nn.Parameter(torch.ones(3					,      config.projection_dim )					,      requires_grad=lowercase_ )

   __A						:							Optional[int]      =						nn.Parameter(torch.ones(17 )					,      requires_grad=lowercase_ )
   __A						:							Tuple      =						nn.Parameter(torch.ones(3 )					,      requires_grad=lowercase_ )



  @torch.no_grad()
  def     A_					(self	:		Optional[int]					,      lowercase_	:		Optional[int]					,      lowercase_	:		Tuple )		->				Union[str, Any]:
   __A						:							List[Any]      =						self.vision_model(lowercase_ )[1]  # pooled_output
   __A						:							List[Any]      =						self.visual_projection(lowercase_ )

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

   __A						:							Any      =						[]
   __A						:							Union[str, Any]      =						image_embeds.shape[0]
   for i in range(lowercase_ ):
    __A						:							Optional[int]      =						{'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
    __A						:							int      =						0.0

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

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

    result.append(lowercase_ )

   __A						:							Tuple      =						[len(res['bad_concepts'] ) > 0 for res in result]

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

   if any(lowercase_ ):
    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     A_					(self	:		Tuple					,      lowercase_	:		torch.FloatTensor					,      lowercase_	:		torch.FloatTensor )		->				str:
   __A						:							str      =						self.vision_model(lowercase_ )[1]  # pooled_output
   __A						:							Union[str, Any]      =						self.visual_projection(lowercase_ )

   __A						:							Any      =						cosine_distance(lowercase_					,      self.special_care_embeds )
   __A						:							Union[str, Any]      =						cosine_distance(lowercase_					,      self.concept_embeds )

   # increase this value to create a stronger `nsfw` filter
   # at the cost of increasing the possibility of filtering benign images
   __A						:							Dict      =						0.0

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

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

   __A						:							Any      =						0.0  # black image

   return images, has_nsfw_concepts













"""simple docstring"""


import importlib.metadata
import subprocess
import sys




def 					a			(  UpperCamelCase_				:					bool = False		)	->		Optional[Any]:
 __A						:							List[Any]      =						False
 if "IPython" in sys.modules:
  __A						:							List[Any]      =						'google.colab' in str(sys.modules['IPython'].get_ipython()		)

 if in_colab:
  if upgrade:
   __A						:							Dict      =						['pip', 'install', '-U', 'torch']
   subprocess.run(UpperCamelCase_  ,						check=UpperCamelCase_		)
  # get the current version of torch
  __A						:							int      =						importlib.metadata.version('torch'		)
  __A						:							int      =						torch_version[: torch_version.rindex('.'		)]
  __A						:							Any      =						F"https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl"
  __A						:							int      =						['pip', 'install', xla_wheel]
  subprocess.run(UpperCamelCase_  ,						check=UpperCamelCase_		)
 else:
  raise RuntimeError('`install_xla` utility works only on google colab.'		)





