
from __future__ import annotations

import matplotlib.pyplot as plt  # type: ignore
import numpy

# initial triangle of Koch snowflake
UpperCamelCase_						:     Tuple	       =							numpy.array([0, 0])
UpperCamelCase_						:     Optional[int]	       =							numpy.array([0.5, 0.866_0254])
UpperCamelCase_						:     Dict	       =							numpy.array([1, 0])
UpperCamelCase_						:     Optional[Any]	       =							[VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]



def 		UpperCamelCase     (       _UpperCAmelCase  :   list[numpy.ndarray] ,			_UpperCAmelCase  :   int  )   ->			list[numpy.ndarray]:






						'''simple docstring'''

						_lowercase       :	Any           =   initial_vectors
						for _ in range(_UpperCAmelCase  ):
												_lowercase       :	Tuple           =   iteration_step(_UpperCAmelCase  )
						return vectors



def 		UpperCamelCase     (       _UpperCAmelCase  :   list[numpy.ndarray]  )   ->			list[numpy.ndarray]:






						'''simple docstring'''

						_lowercase       :	List[str]           =   []
						for i, start_vector in enumerate(vectors[:-1]  ):
												_lowercase       :	List[Any]           =   vectors[i + 1]
												new_vectors.append(_UpperCAmelCase  )
												_lowercase       :	Tuple           =   end_vector - start_vector
												new_vectors.append(start_vector + difference_vector / 3  )
												new_vectors.append(
												    start_vector + difference_vector / 3 + rotate(difference_vector / 3 ,			60  )  )
												new_vectors.append(start_vector + difference_vector * 2 / 3  )
						new_vectors.append(vectors[-1]  )
						return new_vectors



def 		UpperCamelCase     (       _UpperCAmelCase  :   numpy.ndarray ,			_UpperCAmelCase  :   float  )   ->			numpy.ndarray:






						'''simple docstring'''

						_lowercase       :	Any           =   numpy.radians(_UpperCAmelCase  )
						_lowercase      ,    _lowercase       :	Any           =   numpy.cos(_UpperCAmelCase  ), numpy.sin(_UpperCAmelCase  )
						_lowercase       :	Optional[int]           =   numpy.array(((c, -s), (s, c))  )
						return numpy.dot(_UpperCAmelCase ,			_UpperCAmelCase  )



def 		UpperCamelCase     (       _UpperCAmelCase  :   list[numpy.ndarray]  )   ->			None:






						'''simple docstring'''

						_lowercase       :	Dict           =   plt.gca()
						axes.set_aspect("equal"  )

						# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
						# y-coordinates as inputs, which are constructed from the vector-list using
						# zip()
						_lowercase      ,    _lowercase       :	Optional[int]           =   zip(*_UpperCAmelCase  )
						plt.plot(_UpperCAmelCase ,			_UpperCAmelCase  )
						plt.show()


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							UpperCamelCase_						:     Tuple	       =							iterate(INITIAL_VECTORS, 5)
							plot(processed_vectors)






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




