




"""simple docstring"""

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

from ...utils import logging


__lowerCamelCase								=						logging.get_logger(__name__)



def 				a (						__snake_case     :				Tuple,    __snake_case     :				List[str]  ):



    '''simple docstring'''





    UpperCAmelCase_					:List[Any]      			=      nn.functional.normalize(__snake_case  )
    UpperCAmelCase_					:int      			=      nn.functional.normalize(__snake_case  )
    return torch.mm(__snake_case,    normalized_text_embeds.t()  )





class  _snake_case				(							A__       ):

    '''simple docstring'''




    UpperCamelCase__		     =CLIPConfig

    UpperCamelCase__		     =["""CLIPEncoderLayer"""]





    def __init__(							self      :  List[str]					,							snake_case      :  CLIPConfig     ):
        super().__init__(_lowerCAmelCase     )

        UpperCAmelCase_					:Dict      			=      CLIPVisionModel(config.vision_config     )
        UpperCAmelCase_					:Optional[Any]      			=      nn.Linear(config.vision_config.hidden_size					,							config.projection_dim					,							bias=_lowerCAmelCase     )

        UpperCAmelCase_					:List[Any]      			=      nn.Parameter(torch.ones(17					,							config.projection_dim     )					,							requires_grad=_lowerCAmelCase     )
        UpperCAmelCase_					:List[str]      			=      nn.Parameter(torch.ones(3					,							config.projection_dim     )					,							requires_grad=_lowerCAmelCase     )

        UpperCAmelCase_					:Optional[Any]      			=      nn.Parameter(torch.ones(17     )					,							requires_grad=_lowerCAmelCase     )
        UpperCAmelCase_					:str      			=      nn.Parameter(torch.ones(3     )					,							requires_grad=_lowerCAmelCase     )





    @torch.no_grad()
    def 				snake_case_ (							self      :  Optional[Any]					,							snake_case      :  int					,							snake_case      :  Dict     ):
        UpperCAmelCase_					:Any      			=      self.vision_model(_lowerCAmelCase     )[1]  # pooled_output
        UpperCAmelCase_					:str      			=      self.visual_projection(_lowerCAmelCase     )

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

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

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

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

            result.append(_lowerCAmelCase     )

        UpperCAmelCase_					:int      			=      [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]     ):
                    UpperCAmelCase_					:Optional[Any]      			=      torch.zeros_like(images[idx]     )  # black image
                else:
                    UpperCAmelCase_					:Dict      			=      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 				snake_case_ (							self      :  Tuple					,							snake_case      :  torch.FloatTensor					,							snake_case      :  torch.FloatTensor     ):
        UpperCAmelCase_					:Any      			=      self.vision_model(_lowerCAmelCase     )[1]  # pooled_output
        UpperCAmelCase_					:Optional[Any]      			=      self.visual_projection(_lowerCAmelCase     )

        UpperCAmelCase_					:Any      			=      cosine_distance(_lowerCAmelCase					,							self.special_care_embeds     )
        UpperCAmelCase_					:Union[str, Any]      			=      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
        UpperCAmelCase_					:Optional[Any]      			=      0.0

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

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

        UpperCAmelCase_					:Tuple      			=      0.0  # black image

        return images, has_nsfw_concepts








"""simple docstring"""

def 				a (						__snake_case     :				list[list[int]]  ):



				'''simple docstring'''





				if len(__snake_case  ) == 0 or not all(len(__snake_case  ) == 2 for pair in coordinates  ):
								raise ValueError('''The program cannot work out a fitting polynomial.'''  )

				if len({tuple(__snake_case  ) for pair in coordinates}  ) != len(__snake_case  ):
								raise ValueError('''The program cannot work out a fitting polynomial.'''  )

				UpperCAmelCase_					:Optional[Any]      			=      {x for x, _ in coordinates}
				if len(__snake_case  ) == 1:
								return f'x={coordinates[0][0]}'

				if len(__snake_case  ) != len(__snake_case  ):
								raise ValueError('''The program cannot work out a fitting polynomial.'''  )

				UpperCAmelCase_					:List[Any]      			=      len(__snake_case  )

				UpperCAmelCase_					:str      			=      0
				UpperCAmelCase_					:list[list[float]]      			=      []
				# put the x and x to the power values in a matrix
				while count_of_line < x:
								UpperCAmelCase_					:str      			=      0
								UpperCAmelCase_					:Optional[int]      			=      coordinates[count_of_line][0]
								UpperCAmelCase_					:list[float]      			=      []
								while count_in_line < x:
												count_line.append(a ** (x - (count_in_line + 1))  )
												count_in_line += 1
								matrix.append(__snake_case  )
								count_of_line += 1

				UpperCAmelCase_					:Dict      			=      0
				# put the y values into a vector
				UpperCAmelCase_					:list[float]      			=      []
				while count_of_line < x:
								vector.append(coordinates[count_of_line][1]  )
								count_of_line += 1

				UpperCAmelCase_					:Dict      			=      0

				while count < x:
								UpperCAmelCase_					:Any      			=      0
								while zahlen < x:
												if count == zahlen:
																zahlen += 1
												if zahlen == x:
																break
												UpperCAmelCase_					:str      			=      matrix[zahlen][count] / matrix[count][count]
												for counting_columns, item in enumerate(matrix[count]  ):
																# manipulating all the values in the matrix
																matrix[zahlen][counting_columns] -= item * bruch
												# manipulating the values in the vector
												vector[zahlen] -= vector[count] * bruch
												zahlen += 1
								count += 1

				UpperCAmelCase_					:Tuple      			=      0
				# make solutions
				UpperCAmelCase_					:list[str]      			=      []
				while count < x:
								solution.append(str(vector[count] / matrix[count][count]  )  )
								count += 1

				UpperCAmelCase_					:Optional[int]      			=      0
				UpperCAmelCase_					:Optional[Any]      			=      '''f(x)='''

				while count < x:
								UpperCAmelCase_					:list[str]      			=      solution[count].split('''E'''  )
								if len(__snake_case  ) > 1:
												UpperCAmelCase_					:List[Any]      			=      f'{remove_e[0]}*10^{remove_e[1]}'
								solved += f'x^{x - (count + 1)}*{solution[count]}'
								if count + 1 != x:
												solved += "+"
								count += 1

				return solved


if __name__ == "__main__":
						print(points_to_polynomial([]))
						print(points_to_polynomial([[]]))
						print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))
						print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))
						print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))
						print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))
						print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))
						print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
						print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
						print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))


