






import copy
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


snake_case    				=		logging.get_logger(__name__)

snake_case    				=		{
    """microsoft/conditional-detr-resnet-50""": (
        """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json"""
    ),
}


class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase					):
     '''simple docstring'''


     UpperCamelCase_							:		Tuple			=	'''conditional_detr'''
     UpperCamelCase_							:		Tuple			=	['''past_key_values''']
     UpperCamelCase_							:		int			=	{
         '''hidden_size''': '''d_model''',
         '''num_attention_heads''': '''encoder_attention_heads''',
     }


     def __init__(				self       :	Optional[Any]					, UpperCAmelCase_       :	Optional[Any]=True					, UpperCAmelCase_       :	Tuple=None					, UpperCAmelCase_       :	List[str]=3					, UpperCAmelCase_       :	Optional[int]=300					, UpperCAmelCase_       :	List[Any]=6					, UpperCAmelCase_       :	List[Any]=2048					, UpperCAmelCase_       :	str=8					, UpperCAmelCase_       :	List[Any]=6					, UpperCAmelCase_       :	List[str]=2048					, UpperCAmelCase_       :	List[str]=8					, UpperCAmelCase_       :	Tuple=0.0					, UpperCAmelCase_       :	Union[str, Any]=0.0					, UpperCAmelCase_       :	Dict=True					, UpperCAmelCase_       :	str="relu"					, UpperCAmelCase_       :	int=256					, UpperCAmelCase_       :	List[Any]=0.1					, UpperCAmelCase_       :	List[Any]=0.0					, UpperCAmelCase_       :	int=0.0					, UpperCAmelCase_       :	Dict=0.02					, UpperCAmelCase_       :	Optional[int]=1.0					, UpperCAmelCase_       :	Any=False					, UpperCAmelCase_       :	Optional[Any]="sine"					, UpperCAmelCase_       :	Optional[int]="resnet50"					, UpperCAmelCase_       :	List[Any]=True					, UpperCAmelCase_       :	Dict=False					, UpperCAmelCase_       :	Optional[Any]=2					, UpperCAmelCase_       :	Union[str, Any]=5					, UpperCAmelCase_       :	List[Any]=2					, UpperCAmelCase_       :	Optional[int]=1					, UpperCAmelCase_       :	str=1					, UpperCAmelCase_       :	Optional[Any]=2					, UpperCAmelCase_       :	Dict=5					, UpperCAmelCase_       :	Union[str, Any]=2					, UpperCAmelCase_       :	List[str]=0.25					, **UpperCAmelCase_       :	Any					, ):
       if backbone_config is not None and use_timm_backbone:
         raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`."      )

       if not use_timm_backbone:
         if backbone_config is None:
           logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."      )
           SCREAMING_SNAKE_CASE       :      str							=    CONFIG_MAPPING["resnet"](out_features=["stage4"]      )
         elif isinstance(UpperCAmelCase_					, UpperCAmelCase_      ):
           SCREAMING_SNAKE_CASE       :      Optional[Any]							=    backbone_config.get("model_type"      )
           SCREAMING_SNAKE_CASE       :      Optional[int]							=    CONFIG_MAPPING[backbone_model_type]
           SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    config_class.from_dict(UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      str							=    use_timm_backbone
       SCREAMING_SNAKE_CASE       :      List[Any]							=    backbone_config
       SCREAMING_SNAKE_CASE       :      int							=    num_channels
       SCREAMING_SNAKE_CASE       :      List[str]							=    num_queries
       SCREAMING_SNAKE_CASE       :      Dict							=    d_model
       SCREAMING_SNAKE_CASE       :      int							=    encoder_ffn_dim
       SCREAMING_SNAKE_CASE       :      int							=    encoder_layers
       SCREAMING_SNAKE_CASE       :      List[Any]							=    encoder_attention_heads
       SCREAMING_SNAKE_CASE       :      str							=    decoder_ffn_dim
       SCREAMING_SNAKE_CASE       :      List[str]							=    decoder_layers
       SCREAMING_SNAKE_CASE       :      Dict							=    decoder_attention_heads
       SCREAMING_SNAKE_CASE       :      List[Any]							=    dropout
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    attention_dropout
       SCREAMING_SNAKE_CASE       :      List[str]							=    activation_dropout
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    activation_function
       SCREAMING_SNAKE_CASE       :      List[str]							=    init_std
       SCREAMING_SNAKE_CASE       :      Any							=    init_xavier_std
       SCREAMING_SNAKE_CASE       :      Any							=    encoder_layerdrop
       SCREAMING_SNAKE_CASE       :      Tuple							=    decoder_layerdrop
       SCREAMING_SNAKE_CASE       :      List[Any]							=    encoder_layers
       SCREAMING_SNAKE_CASE       :      int							=    auxiliary_loss
       SCREAMING_SNAKE_CASE       :      str							=    position_embedding_type
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    backbone
       SCREAMING_SNAKE_CASE       :      Dict							=    use_pretrained_backbone
       SCREAMING_SNAKE_CASE       :      Any							=    dilation
       # Hungarian matcher
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    class_cost
       SCREAMING_SNAKE_CASE       :      Any							=    bbox_cost
       SCREAMING_SNAKE_CASE       :      List[str]							=    giou_cost
       # Loss coefficients
       SCREAMING_SNAKE_CASE       :      str							=    mask_loss_coefficient
       SCREAMING_SNAKE_CASE       :      int							=    dice_loss_coefficient
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    cls_loss_coefficient
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    bbox_loss_coefficient
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    giou_loss_coefficient
       SCREAMING_SNAKE_CASE       :      str							=    focal_alpha
       super().__init__(is_encoder_decoder=UpperCAmelCase_					, **UpperCAmelCase_      )


     @property
     def 				_A       (				self       :	Any      ):
       return self.encoder_attention_heads


     @property
     def 				_A       (				self       :	Tuple      ):
       return self.d_model






     def 				_A       (				self       :	str      ):
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    copy.deepcopy(self.__dict__      )
       if self.backbone_config is not None:
         SCREAMING_SNAKE_CASE       :      List[Any]							=    self.backbone_config.to_dict()
       SCREAMING_SNAKE_CASE       :      Dict							=    self.__class__.model_type
       return output





class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase					):
     '''simple docstring'''


     UpperCamelCase_							:		Any			=	version.parse('''1.11'''					)


     @property
     def 				_A       (				self       :	Dict      ):
       return OrderedDict(
           [
               ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
               ("pixel_mask", {0: "batch"}),
           ]      )


     @property
     def 				_A       (				self       :	Union[str, Any]      ):
       return 1E-5






     @property
     def 				_A       (				self       :	str      ):
       return 12














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

from ...utils import logging


snake_case    				=		logging.get_logger(__name__)


class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase					):
     '''simple docstring'''


     UpperCamelCase_							:		Union[str, Any]			=	CLIPConfig

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


     def __init__(				self       :	List[Any]					, UpperCAmelCase_       :	CLIPConfig      ):
       super().__init__(UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      Any							=    CLIPVisionModelWithProjection(config.vision_config      )

       SCREAMING_SNAKE_CASE       :      List[Any]							=    nn.Linear(config.vision_config.projection_dim					, 1      )
       SCREAMING_SNAKE_CASE       :      List[str]							=    nn.Linear(config.vision_config.projection_dim					, 1      )






     @torch.no_grad()
     def 				_A       (				self       :	Union[str, Any]					, UpperCAmelCase_       :	int					, UpperCAmelCase_       :	Dict					, UpperCAmelCase_       :	List[Any]=0.5					, UpperCAmelCase_       :	Optional[Any]=0.5      ):
       SCREAMING_SNAKE_CASE       :      str							=    self.vision_model(UpperCAmelCase_      )[0]

       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    self.p_head(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      List[str]							=    nsfw_detected.flatten()
       SCREAMING_SNAKE_CASE       :      List[str]							=    nsfw_detected > p_threshold
       SCREAMING_SNAKE_CASE       :      List[Any]							=    nsfw_detected.tolist()

       if any(UpperCAmelCase_      ):
         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."      )

       for idx, nsfw_detected_ in enumerate(UpperCAmelCase_      ):
         if nsfw_detected_:
           SCREAMING_SNAKE_CASE       :      Dict							=    np.zeros(images[idx].shape      )

       SCREAMING_SNAKE_CASE       :      Any							=    self.w_head(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      List[Any]							=    watermark_detected.flatten()
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    watermark_detected > w_threshold
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    watermark_detected.tolist()

       if any(UpperCAmelCase_      ):
         logger.warning(
             "Potential watermarked content was detected in one or more images. A black image will be returned instead."
             " Try again with a different prompt and/or seed."      )

       for idx, watermark_detected_ in enumerate(UpperCAmelCase_      ):
         if watermark_detected_:
           SCREAMING_SNAKE_CASE       :      Optional[int]							=    np.zeros(images[idx].shape      )

       return images, nsfw_detected, watermark_detected






