



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

from ...utils import logging


SCREAMING_SNAKE_CASE_:str					=						logging.get_logger(__name__)




def      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase		)	->  List[Any]:



    """simple docstring"""






    A			:	List[Any]										=       nn.functional.normalize(_lowerCAmelCase		)
    A			:	List[str]										=       nn.functional.normalize(_lowerCAmelCase		)
    return torch.mm(_lowerCAmelCase				,					normalized_text_embeds.t()		)






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			List[Any] =				CLIPConfig

    __lowerCamelCase      :			Any =				["CLIPEncoderLayer"]






    def __init__(	self,		lowerCamelCase__		):
        super().__init__(lowerCamelCase__		)

        A			:	str										=       CLIPVisionModel(config.vision_config		)
        A			:	Any										=       nn.Linear(config.vision_config.hidden_size,		config.projection_dim,		bias=lowerCamelCase__		)

        A			:	Union[str, Any]										=       nn.Parameter(torch.ones(17,		config.projection_dim		),		requires_grad=lowerCamelCase__		)
        A			:	Optional[int]										=       nn.Parameter(torch.ones(3,		config.projection_dim		),		requires_grad=lowerCamelCase__		)

        A			:	Dict										=       nn.Parameter(torch.ones(17		),		requires_grad=lowerCamelCase__		)
        A			:	Optional[Any]										=       nn.Parameter(torch.ones(3		),		requires_grad=lowerCamelCase__		)






    @torch.no_grad()
    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__		):
        A			:	int										=       self.vision_model(lowerCamelCase__		)[1]  # pooled_output
        A			:	List[str]										=       self.visual_projection(lowerCamelCase__		)

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

        A			:	Union[str, Any]										=       []
        A			:	Tuple										=       image_embeds.shape[0]
        for i in range(lowerCamelCase__		):
            A			:	Any										=       {"""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
            A			:	str										=       0.0

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

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

            result.append(lowerCamelCase__		)

        A			:	List[Any]										=       [len(res["""bad_concepts"""]		) > 0 for res in result]

        return images, has_nsfw_concepts






    @torch.no_grad()
    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__		):
        A			:	Optional[Any]										=       self.vision_model(lowerCamelCase__		)[1]  # pooled_output
        A			:	Optional[Any]										=       self.visual_projection(lowerCamelCase__		)

        A			:	Tuple										=       cosine_distance(lowerCamelCase__,		self.special_care_embeds		)
        A			:	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
        A			:	List[Any]										=       0.0

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

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

        return images, has_nsfw_concepts







from argparse import ArgumentParser

from .env import EnvironmentCommand




def      __UpperCamelCase     (  )	->  Dict:



    """simple docstring"""






    A			:	str										=       ArgumentParser("""Diffusers CLI tool"""				,					usage="""diffusers-cli <command> [<args>]"""		)
    A			:	int										=       parser.add_subparsers(help="""diffusers-cli command helpers"""		)

    # Register commands
    EnvironmentCommand.register_subcommand(_lowerCAmelCase		)

    # Let's go
    A			:	str										=       parser.parse_args()

    if not hasattr(_lowerCAmelCase				,					"""func"""		):
        parser.print_help()
        exit(1		)

    # Run
    A			:	Any										=       args.func(_lowerCAmelCase		)
    service.run()


if __name__ == "__main__":
     main()


