
from __future__ import annotations

from sys import maxsize
from typing import Generic, TypeVar

UpperCamelCase_						:     int	       =							TypeVar("""T""")



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			int:






						'''simple docstring'''

						return (position - 1) // 2



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			int:






						'''simple docstring'''

						return (2 * position) + 1



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			int:






						'''simple docstring'''

						return (2 * position) + 2




class   __lowercase						(						Generic[T]       ):






	def __init__(self				: List[str]    ) ->			None:
							_lowercase       :	list[tuple[T, int]]           =   []
							_lowercase       :	dict[T, int]           =   {}
							_lowercase       :	int           =   0






	def __len__(self				: Optional[Any]    ) ->			int:
							return self.elements






	def __repr__(self				: str    ) ->			str:
							return str(self.heap    )






	def       _a(self				: Optional[Any]    ) ->			bool:
							# Check if the priority queue is empty
							return self.elements == 0






	def       _a(self				: Optional[Any]      ,	snake_case				: T      ,	snake_case				: int    ) ->			None:
							# Add an element with given priority to the queue
							self.heap.append((elem, weight)    )
							_lowercase       :	Optional[Any]           =   self.elements
							self.elements += 1
							self._bubble_up(snake_case    )






	def       _a(self				: Union[str, Any]    ) ->			T:
							# Remove and return the element with lowest weight (highest priority)
							if self.elements > 1:
													self._swap_nodes(0      ,	self.elements - 1    )
							_lowercase      ,    _lowercase       :	Optional[int]           =   self.heap.pop()
							del self.position_map[elem]
							self.elements -= 1
							if self.elements > 0:
													_lowercase      ,    _lowercase       :	Union[str, Any]           =   self.heap[0]
													self._bubble_down(snake_case    )
							return elem






	def       _a(self				: List[Any]      ,	snake_case				: T      ,	snake_case				: int    ) ->			None:
							# Update the weight of the given key
							_lowercase       :	int           =   self.position_map[elem]
							_lowercase       :	str           =   (elem, weight)
							if position > 0:
													_lowercase       :	Any           =   get_parent_position(snake_case    )
													_lowercase      ,    _lowercase       :	Tuple           =   self.heap[parent_position]
													if parent_weight > weight:
																			self._bubble_up(snake_case    )
													else:
																			self._bubble_down(snake_case    )
							else:
													self._bubble_down(snake_case    )






	def       _a(self				: Union[str, Any]      ,	snake_case				: T    ) ->			None:
							# Place a node at the proper position (upward movement) [to be used internally
							# only]
							_lowercase       :	Any           =   self.position_map[elem]
							if curr_pos == 0:
													return None
							_lowercase       :	Any           =   get_parent_position(snake_case    )
							_lowercase      ,    _lowercase       :	Any           =   self.heap[curr_pos]
							_lowercase      ,    _lowercase       :	Union[str, Any]           =   self.heap[parent_position]
							if parent_weight > weight:
													self._swap_nodes(snake_case      ,	snake_case    )
													return self._bubble_up(snake_case    )
							return None






	def       _a(self				: List[str]      ,	snake_case				: T    ) ->			None:
							# Place a node at the proper position (downward movement) [to be used
							# internally only]
							_lowercase       :	str           =   self.position_map[elem]
							_lowercase      ,    _lowercase       :	Union[str, Any]           =   self.heap[curr_pos]
							_lowercase       :	Union[str, Any]           =   get_child_left_position(snake_case    )
							_lowercase       :	str           =   get_child_right_position(snake_case    )
							if child_left_position < self.elements and child_right_position < self.elements:
													_lowercase      ,    _lowercase       :	int           =   self.heap[child_left_position]
													_lowercase      ,    _lowercase       :	str           =   self.heap[child_right_position]
													if child_right_weight < child_left_weight and child_right_weight < weight:
																			self._swap_nodes(snake_case      ,	snake_case    )
																			return self._bubble_down(snake_case    )
							if child_left_position < self.elements:
													_lowercase      ,    _lowercase       :	Tuple           =   self.heap[child_left_position]
													if child_left_weight < weight:
																			self._swap_nodes(snake_case      ,	snake_case    )
																			return self._bubble_down(snake_case    )
							else:
													return None
							if child_right_position < self.elements:
													_lowercase      ,    _lowercase       :	Union[str, Any]           =   self.heap[child_right_position]
													if child_right_weight < weight:
																			self._swap_nodes(snake_case      ,	snake_case    )
																			return self._bubble_down(snake_case    )
							return None






	def       _a(self				: List[str]      ,	snake_case				: int      ,	snake_case				: int    ) ->			None:
							# Swap the nodes at the given positions
							_lowercase       :	Optional[Any]           =   self.heap[nodea_pos][0]
							_lowercase       :	List[str]           =   self.heap[nodea_pos][0]
							_lowercase      ,    _lowercase       :	int           =   (
							    self.heap[nodea_pos],
							    self.heap[nodea_pos],
							)
							_lowercase       :	str           =   nodea_pos
							_lowercase       :	Dict           =   nodea_pos




class   __lowercase						(						Generic[T]       ):






	def __init__(self				: List[str]    ) ->			None:
							_lowercase       :	dict[T, dict[T, int]]           =   {}
							_lowercase       :	int           =   0






	def __repr__(self				: Optional[int]    ) ->			str:
							return str(self.connections    )






	def __len__(self				: Optional[Any]    ) ->			int:
							return self.nodes






	def       _a(self				: Tuple      ,	snake_case				: T    ) ->			None:
							# Add a node in the graph if it is not in the graph
							if node not in self.connections:
													_lowercase       :	Optional[int]           =   {}
													self.nodes += 1






	def       _a(self				: str      ,	snake_case				: T      ,	snake_case				: T      ,	snake_case				: int    ) ->			None:
							# Add an edge between 2 nodes in the graph
							self.add_node(snake_case    )
							self.add_node(snake_case    )
							_lowercase       :	Optional[Any]           =   weight
							_lowercase       :	Optional[int]           =   weight



def 		UpperCamelCase     (       _UpperCAmelCase  :   GraphUndirectedWeighted[T] ,			)   ->			tuple[dict[T, int], dict[T, T | None]]:






						'''simple docstring'''

						_lowercase       :	dict[T, int]           =   {node: maxsize for node in graph.connections}
						_lowercase       :	dict[T, T | None]           =   {node: None for node in graph.connections}

						_lowercase       :	MinPriorityQueue[T]           =   MinPriorityQueue()
						for node, weight in dist.items():
												priority_queue.push(_UpperCAmelCase ,			_UpperCAmelCase  )

						if priority_queue.is_empty():
												return dist, parent

						# initialization
						_lowercase       :	List[str]           =   priority_queue.extract_min()
						_lowercase       :	Tuple           =   0
						for neighbour in graph.connections[node]:
												if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
																		_lowercase       :	Any           =   dist[node] + graph.connections[node][neighbour]
																		priority_queue.update_key(_UpperCAmelCase ,			dist[neighbour]  )
																		_lowercase       :	int           =   node

    # running prim's algorithm
						while not priority_queue.is_empty():
												_lowercase       :	str           =   priority_queue.extract_min()
												for neighbour in graph.connections[node]:
																		if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
																								_lowercase       :	Optional[Any]           =   dist[node] + graph.connections[node][neighbour]
																								priority_queue.update_key(_UpperCAmelCase ,			dist[neighbour]  )
																								_lowercase       :	Any           =   node
						return dist, parent






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

from ...utils import logging


UpperCamelCase_						:     int	       =							logging.get_logger(__name__)



def 		UpperCamelCase     (       _UpperCAmelCase  :   Optional[int] ,			_UpperCAmelCase  :   Dict  )   ->			Any:






						'''simple docstring'''

						_lowercase       :	List[Any]           =   nn.functional.normalize(_UpperCAmelCase  )
						_lowercase       :	List[str]           =   nn.functional.normalize(_UpperCAmelCase  )
						return torch.mm(_UpperCAmelCase ,			normalized_text_embeds.t()  )




class   __lowercase						(						__snake_case       ):
	_A       =   CLIPConfig

	_A       =   ["CLIPEncoderLayer"]






	def __init__(self				: List[str]      ,	snake_case				: CLIPConfig    ) ->			Optional[int]:
							super().__init__(snake_case    )

							_lowercase       :	Tuple           =   CLIPVisionModel(config.vision_config    )
							_lowercase       :	Any           =   nn.Linear(config.vision_config.hidden_size      ,	config.projection_dim      ,	bias=snake_case    )

							_lowercase       :	int           =   nn.Parameter(torch.ones(17      ,	config.projection_dim    )      ,	requires_grad=snake_case    )
							_lowercase       :	str           =   nn.Parameter(torch.ones(3      ,	config.projection_dim    )      ,	requires_grad=snake_case    )

							_lowercase       :	Any           =   nn.Parameter(torch.ones(17    )      ,	requires_grad=snake_case    )
							_lowercase       :	Dict           =   nn.Parameter(torch.ones(3    )      ,	requires_grad=snake_case    )






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

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

							_lowercase       :	List[str]           =   []
							_lowercase       :	int           =   image_embeds.shape[0]
							for i in range(snake_case    ):
													_lowercase       :	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
													_lowercase       :	Optional[int]           =   0.0

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

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

													result.append(snake_case    )

							_lowercase       :	Dict           =   [len(res["bad_concepts"]    ) > 0 for res in result]

							return images, has_nsfw_concepts






	@torch.no_grad()
	def       _a(self				: str      ,	snake_case				: torch.FloatTensor      ,	snake_case				: torch.FloatTensor    ) ->			List[str]:
							_lowercase       :	Dict           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	Any           =   self.visual_projection(snake_case    )

							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.special_care_embeds    )
							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.concept_embeds    )

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							_lowercase       :	Optional[int]           =   0.0

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

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

							return images, has_nsfw_concepts




