




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

from ...utils import logging


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







class 		__UpperCAmelCase(		__A			):





     """simple docstring"""



     __UpperCAmelCase						:			Tuple							=     CLIPConfig

     __UpperCAmelCase						:			Optional[int]							=     ['CLIPEncoderLayer']

     def __init__(   self			:							int    ,					A			:							Optional[Any]     )      ->      Optional[int]:






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

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

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

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

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






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

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

         a__  			=							[]
         a__  			=							image_embeds.shape[0]
         for i in range(__lowercase     ):
             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(__lowercase     )

             result.append(__lowercase     )

         a__  			=							[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]     ):
                     a__  			=							torch.zeros_like(images[idx]     )  # black image
                 else:
                     a__  			=							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 					__SCREAMING_SNAKE_CASE		(   self			:							List[Any]    ,					A			:							Tuple    ,					A			:							Optional[Any]     )      ->      Dict:






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

         a__  			=							cosine_distance(__lowercase    ,					self.special_care_embeds     )
         a__  			=							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
         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










'''simple docstring'''

from ...configuration_utils import PretrainedConfig
from ...utils import is_detectrona_available, logging


_UpperCAmelCase					:			Optional[int]				     =					logging.get_logger(__name__)

_UpperCAmelCase					:			str				     =					{
    """layoutlmv2-base-uncased""": """https://huggingface.co/microsoft/layoutlmv2-base-uncased/resolve/main/config.json""",
    """layoutlmv2-large-uncased""": """https://huggingface.co/microsoft/layoutlmv2-large-uncased/resolve/main/config.json""",
    # See all LayoutLMv2 models at https://huggingface.co/models?filter=layoutlmv2
}

# soft dependency
if is_detectrona_available():
	import detectrona


class    a__					(			__A   ):







				"""simple docstring"""



				__UpperCamelCase     :		List[Any]						=						'layoutlmv2'




				def __init__(self							,      __lowercase=3_05_22							,      __lowercase=7_68							,      __lowercase=12							,      __lowercase=12							,      __lowercase=30_72							,      __lowercase="gelu"							,      __lowercase=0.1							,      __lowercase=0.1							,      __lowercase=5_12							,      __lowercase=2							,      __lowercase=0.0_2							,      __lowercase=1e-12							,      __lowercase=0							,      __lowercase=10_24							,      __lowercase=1_28							,      __lowercase=32							,      __lowercase=True							,      __lowercase=2_56							,      __lowercase=64							,      __lowercase=True							,      __lowercase=[7, 7, 2_56]							,      __lowercase=1_28							,      __lowercase=1_28							,      __lowercase=True							,      __lowercase=True							,      __lowercase=False							,      __lowercase=None							,      **__lowercase							,      ):
										super().__init__(
										    vocab_size=__lowercase							,      hidden_size=__lowercase							,      num_hidden_layers=__lowercase							,      num_attention_heads=__lowercase							,      intermediate_size=__lowercase							,      hidden_act=__lowercase							,      hidden_dropout_prob=__lowercase							,      attention_probs_dropout_prob=__lowercase							,      max_position_embeddings=__lowercase							,      type_vocab_size=__lowercase							,      initializer_range=__lowercase							,      layer_norm_eps=__lowercase							,      pad_token_id=__lowercase							,      **__lowercase							,      )
										__lowerCAmelCase											=					max_ad_position_embeddings
										__lowerCAmelCase											=					max_rel_pos
										__lowerCAmelCase											=					rel_pos_bins
										__lowerCAmelCase											=					fast_qkv
										__lowerCAmelCase											=					max_rel_ad_pos
										__lowerCAmelCase											=					rel_ad_pos_bins
										__lowerCAmelCase											=					convert_sync_batchnorm
										__lowerCAmelCase											=					image_feature_pool_shape
										__lowerCAmelCase											=					coordinate_size
										__lowerCAmelCase											=					shape_size
										__lowerCAmelCase											=					has_relative_attention_bias
										__lowerCAmelCase											=					has_spatial_attention_bias
										__lowerCAmelCase											=					has_visual_segment_embedding
										__lowerCAmelCase											=					(
										    detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
										)




				@classmethod
				def        _snake_case	(self		):
										return {
										    "MODEL.MASK_ON": True,
										    "MODEL.PIXEL_STD": [5_7.3_7_5, 5_7.1_2_0, 5_8.3_9_5],
										    "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
										    "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
										    "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [1_28], [2_56], [5_12]],
										    "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
										    "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 20_00,
										    "MODEL.RPN.PRE_NMS_TOPK_TEST": 10_00,
										    "MODEL.RPN.POST_NMS_TOPK_TRAIN": 10_00,
										    "MODEL.POST_NMS_TOPK_TEST": 10_00,
										    "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
										    "MODEL.ROI_HEADS.NUM_CLASSES": 5,
										    "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
										    "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
										    "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
										    "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
										    "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
										    "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
										    "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
										    "MODEL.RESNETS.DEPTH": 1_01,
										    "MODEL.RESNETS.SIZES": [[32], [64], [1_28], [2_56], [5_12]],
										    "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
										    "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
										    "MODEL.RESNETS.NUM_GROUPS": 32,
										    "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
										    "MODEL.RESNETS.STRIDE_IN_1X1": False,
										}




				def        _snake_case	(self		):
										__lowerCAmelCase											=					detectrona.config.get_cfg()
										for k, v in self.detectrona_config_args.items():
																__lowerCAmelCase											=					k.split('''.'''		)
																__lowerCAmelCase											=					detectrona_config
																for attribute in attributes[:-1]:
																						__lowerCAmelCase											=					getattr(__lowercase							,      __lowercase		)
																setattr(__lowercase							,      attributes[-1]							,      __lowercase		)

										return detectrona_config

