




'''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_ (							__A				: str       ,     __A				: List[str]  ) -> List[str]:
   _SCREAMING_SNAKE_CASE       =      nn.functional.normalize(SCREAMING_SNAKE_CASE_  )
   _SCREAMING_SNAKE_CASE       =      nn.functional.normalize(SCREAMING_SNAKE_CASE_  )
   return torch.mm(SCREAMING_SNAKE_CASE_       ,     normalized_text_embeds.t()  )







class 		lowercase_    ( A   ):


   """simple docstring"""

   lowerCamelCase_				  =						CLIPConfig

   lowerCamelCase_				  =						["""CLIPEncoderLayer"""]



   def __init__(    self					:	str  ,      __lowerCamelCase					:	Optional[int]    ):

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

      _SCREAMING_SNAKE_CASE       =      CLIPVisionModel(config.vision_config    )
      _SCREAMING_SNAKE_CASE       =      nn.Linear(config.vision_config.hidden_size  ,      config.projection_dim  ,      bias=_lowercase    )

      _SCREAMING_SNAKE_CASE       =      nn.Parameter(torch.ones(1_7  ,      config.projection_dim    )  ,      requires_grad=_lowercase    )
      _SCREAMING_SNAKE_CASE       =      nn.Parameter(torch.ones(3  ,      config.projection_dim    )  ,      requires_grad=_lowercase    )

      _SCREAMING_SNAKE_CASE       =      nn.Parameter(torch.ones(1_7    )  ,      requires_grad=_lowercase    )
      _SCREAMING_SNAKE_CASE       =      nn.Parameter(torch.ones(3    )  ,      requires_grad=_lowercase    )



   @torch.no_grad()
   def 							lowerCAmelCase_			(    self					:	Any  ,      __lowerCamelCase					:	str  ,      __lowerCamelCase					:	int    ):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE       =      self.vision_model(_lowercase    )[1]  # pooled_output
      _SCREAMING_SNAKE_CASE       =      self.visual_projection(_lowercase    )

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

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

         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(_lowercase    )

         result.append(_lowercase    )

      _SCREAMING_SNAKE_CASE       =      [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]    ):
               _SCREAMING_SNAKE_CASE       =      torch.zeros_like(images[idx]    )  # black image
            else:
               _SCREAMING_SNAKE_CASE       =      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 							lowerCAmelCase_			(    self					:	List[Any]  ,      __lowerCamelCase					:	Tuple  ,      __lowerCamelCase					:	Optional[int]    ):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE       =      self.vision_model(_lowercase    )[1]  # pooled_output
      _SCREAMING_SNAKE_CASE       =      self.visual_projection(_lowercase    )

      _SCREAMING_SNAKE_CASE       =      cosine_distance(_lowercase  ,      self.special_care_embeds    )
      _SCREAMING_SNAKE_CASE       =      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
      _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.0_1
      _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        lowerCAmelCase(	SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       )->		Tuple:



    """simple docstring"""






    if not root or root not in binary_tree_mirror_dictionary:
        return
    UpperCamelCase_   ,    UpperCamelCase_          =		binary_tree_mirror_dictionary[root][:2]
    UpperCamelCase_          =		[right_child, left_child]
    binary_tree_mirror_dict(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       )
    binary_tree_mirror_dict(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       )




def        lowerCAmelCase(	SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_ = 1       )->		dict:



    """simple docstring"""






    if not binary_tree:
        raise ValueError("binary tree cannot be empty"       )
    if root not in binary_tree:
        UpperCamelCase_          =		f"root {root} is not present in the binary_tree"
        raise ValueError(SCREAMING_SNAKE_CASE_       )
    UpperCamelCase_          =		dict(SCREAMING_SNAKE_CASE_       )
    binary_tree_mirror_dict(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       )
    return binary_tree_mirror_dictionary


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE						:Dict      =			{1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]}
 print(F'''Binary tree: {binary_tree}''')
 SCREAMING_SNAKE_CASE						:str      =			binary_tree_mirror(binary_tree, 5)
 print(F'''Binary tree mirror: {binary_tree_mirror_dictionary}''')
