


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

from ...utils import logging


__UpperCamelCase    :						Union[str, Any]     =							logging.get_logger(__name__)





def   _UpperCAmelCase       (     UpperCAmelCase      :			str						,	UpperCAmelCase      :			List[Any]      ):
      """simple docstring"""




      __lowerCamelCase     :      str       						=						nn.functional.normalize(UpperCAmelCase      )
      __lowerCamelCase     :      str       						=						nn.functional.normalize(UpperCAmelCase      )
      return torch.mm(UpperCAmelCase						,	normalized_text_embeds.t()      )




class 							_UpperCamelCase (						A						):

   '''simple docstring'''







   a_				:							int    = CLIPConfig

   a_				:							Dict    = ["CLIPEncoderLayer"]

   def __init__(  self  : Tuple       ,  _lowerCamelCase  : CLIPConfig							):






         '''simple docstring'''



         super().__init__(_lowerCamelCase							)

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

         __lowerCamelCase     :      Union[str, Any]       						=						nn.Parameter(torch.ones(1_7       ,  config.projection_dim							)       ,  requires_grad=_lowerCamelCase							)
         __lowerCamelCase     :      int       						=						nn.Parameter(torch.ones(3       ,  config.projection_dim							)       ,  requires_grad=_lowerCamelCase							)

         __lowerCamelCase     :      Union[str, Any]       						=						nn.Parameter(torch.ones(1_7							)       ,  requires_grad=_lowerCamelCase							)
         __lowerCamelCase     :      Dict       						=						nn.Parameter(torch.ones(3							)       ,  requires_grad=_lowerCamelCase							)

   @torch.no_grad()
   def   _snake_case    (  self  : Optional[Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : List[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						self.vision_model(_lowerCamelCase							)[1]  # pooled_output
         __lowerCamelCase     :      str       						=						self.visual_projection(_lowerCamelCase							)

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

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

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

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

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

         return images, has_nsfw_concepts


   @torch.no_grad()
   def   _snake_case    (  self  : Tuple       ,  _lowerCamelCase  : torch.FloatTensor       ,  _lowerCamelCase  : torch.FloatTensor							):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						self.vision_model(_lowerCamelCase							)[1]  # pooled_output
         __lowerCamelCase     :      Dict       						=						self.visual_projection(_lowerCamelCase							)

         __lowerCamelCase     :      List[Any]       						=						cosine_distance(_lowerCamelCase       ,  self.special_care_embeds							)
         __lowerCamelCase     :      Optional[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
         __lowerCamelCase     :      List[Any]       						=						0.0

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

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

         return images, has_nsfw_concepts







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


__UpperCamelCase    :						Union[str, Any]     =							{
    'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv2Config'],
    'processing_layoutlmv2': ['LayoutLMv2Processor'],
    'tokenization_layoutlmv2': ['LayoutLMv2Tokenizer'],
}

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __UpperCamelCase    :						List[str]     =							['LayoutLMv2TokenizerFast']

try:
    if not is_vision_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __UpperCamelCase    :						List[str]     =							['LayoutLMv2FeatureExtractor']
    __UpperCamelCase    :						Union[str, Any]     =							['LayoutLMv2ImageProcessor']

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __UpperCamelCase    :						Dict     =							[
        'LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST',
        'LayoutLMv2ForQuestionAnswering',
        'LayoutLMv2ForSequenceClassification',
        'LayoutLMv2ForTokenClassification',
        'LayoutLMv2Layer',
        'LayoutLMv2Model',
        'LayoutLMv2PreTrainedModel',
    ]

if TYPE_CHECKING:
    from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig
    from .processing_layoutlmva import LayoutLMvaProcessor
    from .tokenization_layoutlmva import LayoutLMvaTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

    try:
        if not is_vision_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_layoutlmva import (
            LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST,
            LayoutLMvaForQuestionAnswering,
            LayoutLMvaForSequenceClassification,
            LayoutLMvaForTokenClassification,
            LayoutLMvaLayer,
            LayoutLMvaModel,
            LayoutLMvaPreTrainedModel,
        )
else:
    import sys

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



