


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 							_UpperCAmelCase    (UpperCamelCase__					:  str    ,							UpperCamelCase__					:  Tuple						):
       _A				:	Union[str, Any]       =			nn.functional.normalize(UpperCamelCase__						)
       _A				:	Union[str, Any]       =			nn.functional.normalize(UpperCamelCase__						)
       return torch.mm(UpperCamelCase__    ,							normalized_text_embeds.t()						)







class 					lowerCAmelCase__	(    a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			CLIPConfig

     __SCREAMING_SNAKE_CASE        =			["CLIPEncoderLayer"]


     def __init__(						self			,						__lowerCamelCase)      ->    str:
            super().__init__(__lowerCamelCase)

            _A				:	List[str]       =			CLIPVisionModel(config.vision_config)
            _A				:	List[Any]       =			nn.Linear(config.vision_config.hidden_size			,						config.projection_dim			,						bias=__lowerCamelCase)

            _A				:	Dict       =			nn.Parameter(torch.ones(1_7			,						config.projection_dim)			,						requires_grad=__lowerCamelCase)
            _A				:	str       =			nn.Parameter(torch.ones(3			,						config.projection_dim)			,						requires_grad=__lowerCamelCase)

            _A				:	str       =			nn.Parameter(torch.ones(1_7)			,						requires_grad=__lowerCamelCase)
            _A				:	Optional[int]       =			nn.Parameter(torch.ones(3)			,						requires_grad=__lowerCamelCase)


     @torch.no_grad()
     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase)      ->    Union[str, Any]:
            _A				:	List[Any]       =			self.vision_model(__lowerCamelCase)[1]  # pooled_output
            _A				:	Tuple       =			self.visual_projection(__lowerCamelCase)

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

            _A				:	List[str]       =			[]
            _A				:	str       =			image_embeds.shape[0]
            for i in range(__lowerCamelCase):
                   _A				:	Optional[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				:	Any       =			0.0

                   for concept_idx in range(len(special_cos_dist[0])):
                          _A				:	Optional[int]       =			special_cos_dist[i][concept_idx]
                          _A				:	List[Any]       =			self.special_care_embeds_weights[concept_idx].item()
                          _A				:	Dict       =			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				:	Union[str, Any]       =			0.0_1

                   for concept_idx in range(len(cos_dist[0])):
                          _A				:	Dict       =			cos_dist[i][concept_idx]
                          _A				:	str       =			self.concept_embeds_weights[concept_idx].item()
                          _A				:	Optional[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)

            _A				:	Tuple       =			[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]):
                                 _A				:	Optional[Any]       =			torch.zeros_like(images[idx])  # black image
                          else:
                                 _A				:	str       =			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 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase)      ->    Any:
            _A				:	Union[str, Any]       =			self.vision_model(__lowerCamelCase)[1]  # pooled_output
            _A				:	List[Any]       =			self.visual_projection(__lowerCamelCase)

            _A				:	Optional[int]       =			cosine_distance(__lowerCamelCase			,						self.special_care_embeds)
            _A				:	int       =			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[str]       =			0.0

            _A				:	Union[str, Any]       =			special_cos_dist - self.special_care_embeds_weights + adjustment
            # special_scores = special_scores.round(decimals=3)
            _A				:	int       =			torch.any(special_scores > 0			,						dim=1)
            _A				:	Optional[Any]       =			special_care * 0.0_1
            _A				:	str       =			special_adjustment.unsqueeze(1).expand(-1			,						cos_dist.shape[1])

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

            _A				:	List[str]       =			0.0  # black image

            return images, has_nsfw_concepts




import warnings

from .generation import FlaxGenerationMixin







class 					lowerCAmelCase__	(    a):




     '''simple docstring'''
     # warning at import time
     warnings.warn(
         "Importing `FlaxGenerationMixin` from `src/transformers/generation_flax_utils.py` is deprecated and will "
         "be removed in Transformers v5. Import as `from transformers import FlaxGenerationMixin` instead."					,   a					,   )
