





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

from ...utils import logging


_UpperCamelCase       :				Union[str, Any]           =			logging.get_logger(__name__)
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		Tuple:


   '''simple docstring'''







   __A    =  nn.functional.normalize(snake_case      )
   __A    =  nn.functional.normalize(snake_case      )
   return torch.mm(snake_case							,			normalized_text_embeds.t()      )







class 		_lowerCAmelCase(		_a):

  """simple docstring"""







  lowerCamelCase__     	=       CLIPConfig

  lowerCamelCase__     	=       ['''CLIPEncoderLayer''']

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

     __A    =  CLIPVisionModel(config.vision_config      )
     __A    =  nn.Linear(config.vision_config.hidden_size    ,							config.projection_dim    ,							bias=UpperCAmelCase      )

     __A    =  nn.Parameter(torch.ones(17    ,							config.projection_dim      )    ,							requires_grad=UpperCAmelCase      )
     __A    =  nn.Parameter(torch.ones(3    ,							config.projection_dim      )    ,							requires_grad=UpperCAmelCase      )

     __A    =  nn.Parameter(torch.ones(17      )    ,							requires_grad=UpperCAmelCase      )
     __A    =  nn.Parameter(torch.ones(3      )    ,							requires_grad=UpperCAmelCase      )

  @torch.no_grad()
  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   str:
     __A    =  self.vision_model(UpperCAmelCase      )[1]  # pooled_output
     __A    =  self.visual_projection(UpperCAmelCase      )

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

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

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

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

        result.append(UpperCAmelCase      )

     __A    =  [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]      ):
              __A    =  torch.zeros_like(images[idx]      )  # black image
           else:
              __A    =  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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   Optional[int]:
     __A    =  self.vision_model(UpperCAmelCase      )[1]  # pooled_output
     __A    =  self.visual_projection(UpperCAmelCase      )

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

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

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

     __A    =  0.0  # black image

     return images, has_nsfw_concepts








from collections import deque
def  __UpperCamelCase    (						snake_case      )    ->		List[str]:


   '''simple docstring'''







   return input(snake_case      ).strip().split(''' '''      )
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		dict[int, list[int]]:


   '''simple docstring'''







   __A    =  {}
   for i in range(snake_case      ):
      __A    =  []

   for e in range(snake_case      ):
      __A   ,		__A    =  (int(snake_case      ) for i in _input(F"Edge {e + 1}: <node1> <node2> "      ))
      graph[x].append(snake_case      )
   return graph
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		dict[int, list[int]]:


   '''simple docstring'''







   __A    =  {}
   for i in range(snake_case      ):
      __A    =  []

   for e in range(snake_case      ):
      __A   ,		__A    =  (int(snake_case      ) for i in _input(F"Edge {e + 1}: <node1> <node2> "      ))
      graph[x].append(snake_case      )
      graph[y].append(snake_case      )
   return graph
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		dict[int, list[tuple[int, int]]]:


   '''simple docstring'''







   __A    =  {}
   for i in range(snake_case      ):
      __A    =  []

   for e in range(snake_case      ):
      __A   ,		__A   ,		__A    =  (int(snake_case      ) for i in _input(F"Edge {e + 1}: <node1> <node2> <weight> "      ))
      graph[x].append((y, w)      )
      graph[y].append((x, w)      )
   return graph


if __name__ == "__main__":
    _UpperCamelCase       ,    _UpperCamelCase       :				List[Any]           =			(int(i) for i in _input("""Number of nodes and edges: """))

    _UpperCamelCase       :				int           =			int(
        _input(
            """Press 1 or 2 or 3 \n"""
            """1. Unweighted directed \n"""
            """2. Unweighted undirected \n"""
            """3. Weighted undirected \n"""
        )[0]
    )

    _UpperCamelCase       :				Optional[Any]           =			{
        1: initialize_unweighted_directed_graph,
        2: initialize_unweighted_undirected_graph,
        3: initialize_weighted_undirected_graph,
    }[graph_choice](n, m)
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		int:


   '''simple docstring'''







   __A   ,		__A    =  {s}, [s]
   print(snake_case      )
   while _s:
      __A    =  0
      for i in g[_s[-1]]:
         if i not in vis:
            _s.append(snake_case      )
            vis.add(snake_case      )
            __A    =  1
            print(snake_case      )
            break
      if not flag:
         _s.pop()
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		Dict:


   '''simple docstring'''







   __A   ,		__A    =  {s}, deque([s]      )
   print(snake_case      )
   while q:
      __A    =  q.popleft()
      for v in g[u]:
         if v not in vis:
            vis.add(snake_case      )
            q.append(snake_case      )
            print(snake_case      )
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		List[Any]:


   '''simple docstring'''







   __A   ,		__A   ,		__A    =  {s: 0}, set(), {s: 0}
   while True:
      if len(snake_case      ) == len(snake_case      ) - 1:
         break
      __A    =  1_0_0_0_0_0
      for i in dist:
         if i not in known and dist[i] < mini:
            __A    =  dist[i]
            __A    =  i
      known.add(snake_case      )
      for v in g[u]:
         if v[0] not in known and dist[u] + v[1] < dist.get(v[0]							,			1_0_0_0_0_0      ):
            __A    =  dist[u] + v[1]
            __A    =  u
   for i in dist:
      if i != s:
         print(dist[i]      )
def  __UpperCamelCase    (						snake_case							,			snake_case=None							,			snake_case=None      )    ->		Any:


   '''simple docstring'''







   if q is None:
      __A    =  [1]
   if ind is None:
      __A    =  [0] * (len(snake_case      ) + 1)  # SInce oth Index is ignored
      for u in g:
         for v in g[u]:
            ind[v] += 1
      __A    =  deque()
      for i in g:
         if ind[i] == 0:
            q.append(snake_case      )
   if len(snake_case      ) == 0:
      return
   __A    =  q.popleft()
   print(snake_case      )
   for w in g[v]:
      ind[w] -= 1
      if ind[w] == 0:
         q.append(snake_case      )
   topo(snake_case							,			snake_case							,			snake_case      )
def  __UpperCamelCase    (						)    ->		Any:


   '''simple docstring'''







   __A    =  input().strip()
   __A    =  []
   for _ in range(snake_case      ):
      a.append(map(snake_case							,			input().strip().split()      )      )
   return a, n
def  __UpperCamelCase    (						snake_case      )    ->		List[Any]:


   '''simple docstring'''







   ((__A)   ,		(__A))    =  a_and_n
   __A    =  list(snake_case      )
   __A    =  [[0] * n for i in range(snake_case      )]
   for k in range(snake_case      ):
      for i in range(snake_case      ):
         for j in range(snake_case      ):
            if dist[i][j] > dist[i][k] + dist[k][j]:
               __A    =  dist[i][k] + dist[k][j]
               __A    =  k
   print(snake_case      )
def  __UpperCamelCase    (						snake_case							,			snake_case      )    ->		Dict:


   '''simple docstring'''







   __A   ,		__A   ,		__A    =  {s: 0}, set(), {s: 0}
   while True:
      if len(snake_case      ) == len(snake_case      ) - 1:
         break
      __A    =  1_0_0_0_0_0
      for i in dist:
         if i not in known and dist[i] < mini:
            __A    =  dist[i]
            __A    =  i
      known.add(snake_case      )
      for v in g[u]:
         if v[0] not in known and v[1] < dist.get(v[0]							,			1_0_0_0_0_0      ):
            __A    =  v[1]
            __A    =  u
   return dist
def  __UpperCamelCase    (						)    ->		List[str]:


   '''simple docstring'''







   __A   ,		__A    =  map(snake_case							,			input().split(''' '''      )      )
   __A    =  []
   for _ in range(snake_case      ):
      edges.append(map(snake_case							,			input().split(''' '''      )      )      )
   return edges, n
def  __UpperCamelCase    (						snake_case      )    ->		int:


   '''simple docstring'''







   ((__A)   ,		(__A))    =  e_and_n
   e.sort(reverse=snake_case							,			key=lambda snake_case      : x[2]      )
   __A    =  [{i} for i in range(1							,			n + 1      )]
   while True:
      if len(snake_case      ) == 1:
         break
      print(snake_case      )
      __A    =  e.pop()
      for i in range(len(snake_case      )      ):
         if x[0] in s[i]:
            break
      for j in range(len(snake_case      )      ):
         if x[1] in s[j]:
            if i == j:
               break
            s[j].update(s[i]      )
            s.pop(snake_case      )
            break
def  __UpperCamelCase    (						snake_case      )    ->		Tuple:


   '''simple docstring'''







   __A    =  []
   for node in graph:
      if not graph[node]:
         isolated.append(snake_case      )
   return isolated

