




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

from ...utils import logging


SCREAMING_SNAKE_CASE_						:					Any			   =       logging.get_logger(__name__)
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_		)     ->   List[Any]:
    a__      =       nn.functional.normalize(UpperCAmelCase_		)
    a__      =       nn.functional.normalize(UpperCAmelCase_		)
    return torch.mm(UpperCAmelCase_   ,    normalized_text_embeds.t()		)







class 		__UpperCAmelCase(		lowercase__ ):





     """simple docstring"""



     __UpperCAmelCase	: Optional[Any]						=    CLIPConfig

     __UpperCAmelCase	: List[Any]						=    ["""CLIPEncoderLayer"""]

     def __init__(      self :       Tuple						,				A :       CLIPConfig    )			->			Any:






         """simple docstring"""
         super().__init__(A    )

         a__      =       CLIPVisionModel(config.vision_config    )
         a__      =       nn.Linear(config.vision_config.hidden_size						,				config.projection_dim						,				bias=A    )

         a__      =       nn.Parameter(torch.ones(17						,				config.projection_dim    )						,				requires_grad=A    )
         a__      =       nn.Parameter(torch.ones(3						,				config.projection_dim    )						,				requires_grad=A    )

         a__      =       nn.Parameter(torch.ones(17    )						,				requires_grad=A    )
         a__      =       nn.Parameter(torch.ones(3    )						,				requires_grad=A    )

     @torch.no_grad()
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]						,				A :       List[Any]						,				A :       Dict    )			->			List[Any]:






         """simple docstring"""
         a__      =       self.vision_model(A    )[1]  # pooled_output
         a__      =       self.visual_projection(A    )

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

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

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

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

             result.append(A    )

         a__      =       [len(res["""bad_concepts"""]    ) > 0 for res in result]

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

         if any(A    ):
             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 				__SCREAMING_SNAKE_CASE		(      self :       Dict						,				A :       torch.FloatTensor						,				A :       torch.FloatTensor    )			->			Any:






         """simple docstring"""
         a__      =       self.vision_model(A    )[1]  # pooled_output
         a__      =       self.visual_projection(A    )

         a__      =       cosine_distance(A						,				self.special_care_embeds    )
         a__      =       cosine_distance(A						,				self.concept_embeds    )

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

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

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

         a__      =       0.0  # black image

         return images, has_nsfw_concepts












from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE_						:					str			   =       {
    '''configuration_wav2vec2_conformer''': [
        '''WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''Wav2Vec2ConformerConfig''',
    ],
}


try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE_						:					Optional[int]			   =       [
     '''WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''Wav2Vec2ConformerForAudioFrameClassification''',
     '''Wav2Vec2ConformerForCTC''',
     '''Wav2Vec2ConformerForPreTraining''',
     '''Wav2Vec2ConformerForSequenceClassification''',
     '''Wav2Vec2ConformerForXVector''',
     '''Wav2Vec2ConformerModel''',
     '''Wav2Vec2ConformerPreTrainedModel''',
 ]

if TYPE_CHECKING:
 from .configuration_wavaveca_conformer import (
     WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
     WavaVecaConformerConfig,
 )

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_wavaveca_conformer import (
      WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      WavaVecaConformerForAudioFrameClassification,
      WavaVecaConformerForCTC,
      WavaVecaConformerForPreTraining,
      WavaVecaConformerForSequenceClassification,
      WavaVecaConformerForXVector,
      WavaVecaConformerModel,
      WavaVecaConformerPreTrainedModel,
  )

else:
 import sys

 SCREAMING_SNAKE_CASE_						:					Optional[int]			   =       _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






