






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

from ...utils import logging


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






def   a      (						lowerCamelCase_		,       lowerCamelCase_    ):






				'''simple docstring'''
				lowercase__       			=      nn.functional.normalize(lowerCamelCase_    )
				lowercase__       			=      nn.functional.normalize(lowerCamelCase_    )
				return torch.mm(lowerCamelCase_		,       normalized_text_embeds.t()    )




class 				_UpperCAmelCase (	A__     ):

				"""simple docstring"""




				lowercase__    							=	CLIPConfig

				lowercase__    							=	["""CLIPEncoderLayer"""]




				def __init__(					self						:   Any,  lowerCamelCase						:   CLIPConfig  ):

								'''simple docstring'''
								super().__init__(lowerCamelCase  )

								lowercase__       			=      CLIPVisionModel(config.vision_config  )
								lowercase__       			=      nn.Linear(config.vision_config.hidden_size,  config.projection_dim,  bias=lowerCamelCase  )

								lowercase__       			=      nn.Parameter(torch.ones(17,  config.projection_dim  ),  requires_grad=lowerCamelCase  )
								lowercase__       			=      nn.Parameter(torch.ones(3,  config.projection_dim  ),  requires_grad=lowerCamelCase  )

								lowercase__       			=      nn.Parameter(torch.ones(17  ),  requires_grad=lowerCamelCase  )
								lowercase__       			=      nn.Parameter(torch.ones(3  ),  requires_grad=lowerCamelCase  )




				@torch.no_grad()
				def     lowercase__       (					self						:   Union[str, Any],  lowerCamelCase						:   Optional[Any],  lowerCamelCase						:   int  ):

								'''simple docstring'''
								lowercase__       			=      self.vision_model(lowerCamelCase  )[1]  # pooled_output
								lowercase__       			=      self.visual_projection(lowerCamelCase  )

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

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

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

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

												result.append(lowerCamelCase  )

								lowercase__       			=      [len(res['''bad_concepts''']  ) > 0 for res in result]

								for idx, has_nsfw_concept in enumerate(lowerCamelCase  ):
												if has_nsfw_concept:
																if torch.is_tensor(lowerCamelCase  ) or torch.is_tensor(images[0]  ):
																				lowercase__       			=      torch.zeros_like(images[idx]  )  # black image
																else:
																				lowercase__       			=      np.zeros(images[idx].shape  )  # black image

								if any(lowerCamelCase  ):
												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     lowercase__       (					self						:   Optional[Any],  lowerCamelCase						:   torch.FloatTensor,  lowerCamelCase						:   torch.FloatTensor  ):

								'''simple docstring'''
								lowercase__       			=      self.vision_model(lowerCamelCase  )[1]  # pooled_output
								lowercase__       			=      self.visual_projection(lowerCamelCase  )

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

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

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

								lowercase__       			=      0.0  # black image

								return images, has_nsfw_concepts












import numpy as np
class 				_UpperCAmelCase :

				"""simple docstring"""




				def __init__(					self						:   Union[str, Any],  lowerCamelCase						:   int=5,  lowerCamelCase						:   Optional[Any]=5  ):

								'''simple docstring'''
								lowercase__       			=      depth
								lowercase__       			=      0
								lowercase__       			=      None
								lowercase__       			=      None
								lowercase__       			=      min_leaf_size
								lowercase__       			=      None




				def     lowercase__       (					self						:   Union[str, Any],  lowerCamelCase						:   Tuple,  lowerCamelCase						:   Dict  ):

								'''simple docstring'''
								if labels.ndim != 1:
												print('''Error: Input labels must be one dimensional'''  )

								return np.mean((labels - prediction) ** 2  )




				def     lowercase__       (					self						:   Tuple,  lowerCamelCase						:   List[str],  lowerCamelCase						:   Tuple  ):

								'''simple docstring'''
								if x.ndim != 1:
												print('''Error: Input data set must be one dimensional'''  )
												return
								if len(lowerCamelCase  ) != len(lowerCamelCase  ):
												print('''Error: X and y have different lengths'''  )
												return
								if y.ndim != 1:
												print('''Error: Data set labels must be one dimensional'''  )
												return

								if len(lowerCamelCase  ) < 2 * self.min_leaf_size:
												lowercase__       			=      np.mean(lowerCamelCase  )
												return

								if self.depth == 1:
												lowercase__       			=      np.mean(lowerCamelCase  )
												return

								lowercase__       			=      0
								lowercase__       			=      self.mean_squared_error(lowerCamelCase,  np.mean(lowerCamelCase  )  ) * 2
								for i in range(len(lowerCamelCase  )  ):
												if len(x[:i]  ) < self.min_leaf_size:
																continue
												elif len(x[i:]  ) < self.min_leaf_size:
																continue
												else:
																lowercase__       			=      self.mean_squared_error(x[:i],  np.mean(y[:i]  )  )
																lowercase__       			=      self.mean_squared_error(x[i:],  np.mean(y[i:]  )  )
																lowercase__       			=      error_left + error_right
																if error < min_error:
																				lowercase__       			=      i
																				lowercase__       			=      error

								if best_split != 0:
												lowercase__       			=      x[:best_split]
												lowercase__       			=      y[:best_split]
												lowercase__       			=      x[best_split:]
												lowercase__       			=      y[best_split:]

												lowercase__       			=      x[best_split]
												lowercase__       			=      DecisionTree(
												    depth=self.depth - 1,  min_leaf_size=self.min_leaf_size  )
												lowercase__       			=      DecisionTree(
												    depth=self.depth - 1,  min_leaf_size=self.min_leaf_size  )
												self.left.train(lowerCamelCase,  lowerCamelCase  )
												self.right.train(lowerCamelCase,  lowerCamelCase  )
								else:
												lowercase__       			=      np.mean(lowerCamelCase  )

								return




				def     lowercase__       (					self						:   Optional[Any],  lowerCamelCase						:   Tuple  ):

								'''simple docstring'''
								if self.prediction is not None:
												return self.prediction
								elif self.left or self.right is not None:
												if x >= self.decision_boundary:
																return self.right.predict(lowerCamelCase  )
												else:
																return self.left.predict(lowerCamelCase  )
								else:
												print('''Error: Decision tree not yet trained'''  )
												return None



class 				_UpperCAmelCase :

				"""simple docstring"""




				@staticmethod
				def     lowercase__       (					lowerCamelCase						:   int,  lowerCamelCase						:   str  ):

								'''simple docstring'''
								lowercase__       			=      float(0  )
								for label in labels:
												squared_error_sum += (label - prediction) ** 2

								return float(squared_error_sum / labels.size  )






def   a      (						):






				'''simple docstring'''
				lowercase__       			=      np.arange(-1.0		,       1.0		,       0.0_05    )
				lowercase__       			=      np.sin(lowerCamelCase_    )

				lowercase__       			=      DecisionTree(depth=10		,       min_leaf_size=10    )
				tree.train(lowerCamelCase_		,       lowerCamelCase_    )

				lowercase__       			=      (np.random.rand(10    ) * 2) - 1
				lowercase__       			=      np.array([tree.predict(lowerCamelCase_    ) for x in test_cases]    )
				lowercase__       			=      np.mean((predictions - test_cases) ** 2    )

				print('''Test values: ''' + str(lowerCamelCase_    )    )
				print('''Predictions: ''' + str(lowerCamelCase_    )    )
				print('''Average error: ''' + str(lowerCamelCase_    )    )


if __name__ == "__main__":
							main()
							import doctest

							doctest.testmod(name='mean_squarred_error', verbose=True)




