

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

from ...utils import logging


A_						:     str			  =				logging.get_logger(__name__)


def  __a    (				SCREAMING_SNAKE_CASE    ,				SCREAMING_SNAKE_CASE ) ->       List[Any]:






    '''simple docstring'''
    __UpperCAmelCase			   =     nn.functional.normalize(SCREAMING_SNAKE_CASE )
    __UpperCAmelCase			   =     nn.functional.normalize(SCREAMING_SNAKE_CASE )
    return torch.mm(SCREAMING_SNAKE_CASE    ,				normalized_text_embeds.t() )
class    A_				( _a  ):


    '''simple docstring'''






    a__       							=    CLIPConfig

    a__       							=    ["CLIPEncoderLayer"]


    def __init__(self       , lowercase__					)       -> Optional[Any]:
        super().__init__(lowercase__					)

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

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

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


    @torch.no_grad()
    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__					)       -> Optional[Any]:
        __UpperCAmelCase			   =     self.vision_model(lowercase__					)[1]  # pooled_output
        __UpperCAmelCase			   =     self.visual_projection(lowercase__					)

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

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

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

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

            result.append(lowercase__					)

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

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

        if any(lowercase__					):
            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        lowerCAmelCase_  (self       , lowercase__       , lowercase__					)       -> Optional[Any]:
        __UpperCAmelCase			   =     self.vision_model(lowercase__					)[1]  # pooled_output
        __UpperCAmelCase			   =     self.visual_projection(lowercase__					)

        __UpperCAmelCase			   =     cosine_distance(lowercase__       , self.special_care_embeds					)
        __UpperCAmelCase			   =     cosine_distance(lowercase__       , self.concept_embeds					)

        # increase this value to create a stronger `nsfw` filter
        # at the cost of increasing the possibility of filtering benign images
        __UpperCAmelCase			   =     0.0

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

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

        __UpperCAmelCase			   =     0.0  # black image

        return images, has_nsfw_concepts







from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available
@dataclass
class    A_				( _a  ):


    '''simple docstring'''






    a__       							=    {
        "sld_warmup_steps": 15,
        "sld_guidance_scale": 20,
        "sld_threshold": 0.0,
        "sld_momentum_scale": 0.0,
        "sld_mom_beta": 0.0,
    }
    a__       							=    {
        "sld_warmup_steps": 10,
        "sld_guidance_scale": 10_00,
        "sld_threshold": 0.01,
        "sld_momentum_scale": 0.3,
        "sld_mom_beta": 0.4,
    }
    a__       							=    {
        "sld_warmup_steps": 7,
        "sld_guidance_scale": 20_00,
        "sld_threshold": 0.0_25,
        "sld_momentum_scale": 0.5,
        "sld_mom_beta": 0.7,
    }
    a__       							=    {
        "sld_warmup_steps": 0,
        "sld_guidance_scale": 50_00,
        "sld_threshold": 1.0,
        "sld_momentum_scale": 0.5,
        "sld_mom_beta": 0.7,
    }






@dataclass
class    A_				( _a  ):


    '''simple docstring'''






    a__       							=    42
    a__       							=    42
    a__       							=    42
    a__       							=    42


if is_transformers_available() and is_torch_available():
       from .pipeline_stable_diffusion_safe import StableDiffusionPipelineSafe
       from .safety_checker import SafeStableDiffusionSafetyChecker




