

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

from ...utils import logging


lowerCAmelCase							:  List[str]   	=						logging.get_logger(__name__)







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						SCREAMING_SNAKE_CASE_: Optional[Any]  		=       nn.functional.normalize(_UpperCAmelCase    )
						SCREAMING_SNAKE_CASE_: List[Any]  		=       nn.functional.normalize(_UpperCAmelCase    )
						return torch.mm(_UpperCAmelCase				,	normalized_text_embeds.t()    )



class   __lowercase				( UpperCAmelCase_	):




			"""simple docstring"""







			_UpperCAmelCase   :							str										=     CLIPConfig

			_UpperCAmelCase   :							Optional[int]										=     ['''CLIPEncoderLayer''']



			def __init__( self  :     List[Any]   ,						lowerCAmelCase__  :     CLIPConfig):
									super().__init__(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       CLIPVisionModel(config.vision_config)
									SCREAMING_SNAKE_CASE_: List[str]  		=       nn.Linear(config.vision_config.hidden_size   ,						config.projection_dim   ,						bias=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       nn.Parameter(torch.ones(17   ,						config.projection_dim)   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       nn.Parameter(torch.ones(3   ,						config.projection_dim)   ,						requires_grad=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       nn.Parameter(torch.ones(17)   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Tuple  		=       nn.Parameter(torch.ones(3)   ,						requires_grad=lowerCAmelCase__)



			@torch.no_grad()
			def        _SCREAMING_SNAKE_CASE			( self  :     int   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.visual_projection(lowerCAmelCase__)

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

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       []
									SCREAMING_SNAKE_CASE_: List[Any]  		=       image_embeds.shape[0]
									for i in range(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_: Dict  		=       {"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_: List[Any]  		=       0.0

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

															for concept_idx in range(len(cos_dist[0])):
																					SCREAMING_SNAKE_CASE_: List[str]  		=       cos_dist[i][concept_idx]
																					SCREAMING_SNAKE_CASE_: Any  		=       self.concept_embeds_weights[concept_idx].item()
																					SCREAMING_SNAKE_CASE_: Optional[int]  		=       round(concept_cos - concept_threshold + adjustment   ,						3)
																					if result_img["concept_scores"][concept_idx] > 0:
																											result_img["bad_concepts"].append(lowerCAmelCase__)

															result.append(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Tuple  		=       [len(res["bad_concepts"]) > 0 for res in result]

									return images, has_nsfw_concepts




			@torch.no_grad()
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]   ,						lowerCAmelCase__  :     torch.FloatTensor   ,						lowerCAmelCase__  :     torch.FloatTensor):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.visual_projection(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Any  		=       cosine_distance(lowerCAmelCase__   ,						self.special_care_embeds)
									SCREAMING_SNAKE_CASE_: str  		=       cosine_distance(lowerCAmelCase__   ,						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_: Dict  		=       0.0

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

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

									return images, has_nsfw_concepts














import math

class 						lowerCAmelCase   :

					'''simple docstring'''

					def __init__(     self :		Tuple						,   __a :		int=0							)	->     Optional[Any]:  # a graph with Node 0,1,...,N-1


												"""simple docstring"""

												__lowercase					:							Any			=   n
												__lowercase					:							Optional[int]			=   [
												    [math.inf for j in range(0						,   __a							)] for i in range(0						,   __a							)
												]  # adjacency matrix for weight
												__lowercase					:							Dict			=   [
												    [math.inf for j in range(0						,   __a							)] for i in range(0						,   __a							)
												]  # dp[i][j] stores minimum distance from i to j



					def 					lowerCAmelCase (     self :		int						,   __a :		Optional[int]						,   __a :		Tuple						,   __a :		Dict							)	->     Dict:


												"""simple docstring"""

												__lowercase					:							Any			=   w



					def 					lowerCAmelCase (     self :		List[str]							)	->     Tuple:


												"""simple docstring"""

												for k in range(0						,   self.n							):
																			for i in range(0						,   self.n							):
																										for j in range(0						,   self.n							):
																																	__lowercase					:							List[str]			=   min(self.dp[i][j]						,   self.dp[i][k] + self.dp[k][j]							)



					def 					lowerCAmelCase (     self :		Any						,   __a :		Any						,   __a :		str							)	->     int:


												"""simple docstring"""

												return self.dp[u][v]


if __name__ == "__main__":
	lowerCamelCase       :       int        =				Graph(5)
	graph.add_edge(0, 2, 9)
	graph.add_edge(0, 4, 10)
	graph.add_edge(1, 3, 5)
	graph.add_edge(2, 3, 7)
	graph.add_edge(3, 0, 10)
	graph.add_edge(3, 1, 2)
	graph.add_edge(3, 2, 1)
	graph.add_edge(3, 4, 6)
	graph.add_edge(4, 1, 3)
	graph.add_edge(4, 2, 4)
	graph.add_edge(4, 3, 9)
	graph.floyd_warshall()
	graph.show_min(1, 4)
	graph.show_min(0, 3)