



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case    				=		logging.get_logger(__name__)

snake_case    				=		{
    """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""",
}


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


     UpperCamelCase_							:		Union[str, Any]			=	"git_vision_model"


     def __init__(				self       :	int					, UpperCAmelCase_       :	Optional[Any]=768					, UpperCAmelCase_       :	Any=3072					, UpperCAmelCase_       :	Optional[Any]=12					, UpperCAmelCase_       :	List[str]=12					, UpperCAmelCase_       :	Any=3					, UpperCAmelCase_       :	List[Any]=224					, UpperCAmelCase_       :	List[Any]=16					, UpperCAmelCase_       :	str="quick_gelu"					, UpperCAmelCase_       :	List[Any]=1E-5					, UpperCAmelCase_       :	List[str]=0.0					, UpperCAmelCase_       :	Any=0.02					, **UpperCAmelCase_       :	str					, ):
       super().__init__(**_lowerCamelCase      )

       SCREAMING_SNAKE_CASE       :      List[str]							=    hidden_size
       SCREAMING_SNAKE_CASE       :      List[str]							=    intermediate_size
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    num_hidden_layers
       SCREAMING_SNAKE_CASE       :      List[Any]							=    num_attention_heads
       SCREAMING_SNAKE_CASE       :      Tuple							=    num_channels
       SCREAMING_SNAKE_CASE       :      List[Any]							=    patch_size
       SCREAMING_SNAKE_CASE       :      Dict							=    image_size
       SCREAMING_SNAKE_CASE       :      int							=    initializer_range
       SCREAMING_SNAKE_CASE       :      List[str]							=    attention_dropout
       SCREAMING_SNAKE_CASE       :      Dict							=    layer_norm_eps
       SCREAMING_SNAKE_CASE       :      List[str]							=    hidden_act






     @classmethod
     def 				_A       (				cls       :	Dict					, UpperCAmelCase_       :	Tuple					, **UpperCAmelCase_       :	str      ):
       cls._set_token_in_kwargs(_lowerCamelCase      )

       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Dict							=    cls.get_config_dict(_lowerCamelCase					, **_lowerCamelCase      )

       # get the vision config dict if we are loading from GITConfig
       if config_dict.get("model_type"      ) == "git":
         SCREAMING_SNAKE_CASE       :      Tuple							=    config_dict["vision_config"]

       if "model_type" in config_dict and hasattr(cls					, "model_type"      ) and config_dict["model_type"] != cls.model_type:
         logger.warning(
             f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
             f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.'''      )

       return cls.from_dict(_lowerCamelCase					, **_lowerCamelCase      )





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


     UpperCamelCase_							:		Dict			=	"git"


     def __init__(				self       :	List[Any]					, UpperCAmelCase_       :	Any=None					, UpperCAmelCase_       :	int=3_0522					, UpperCAmelCase_       :	Tuple=768					, UpperCAmelCase_       :	Dict=6					, UpperCAmelCase_       :	int=12					, UpperCAmelCase_       :	int=3072					, UpperCAmelCase_       :	List[str]="gelu"					, UpperCAmelCase_       :	List[Any]=0.1					, UpperCAmelCase_       :	Union[str, Any]=0.1					, UpperCAmelCase_       :	List[str]=1024					, UpperCAmelCase_       :	Optional[Any]=0.02					, UpperCAmelCase_       :	List[str]=1E-12					, UpperCAmelCase_       :	Dict=0					, UpperCAmelCase_       :	List[Any]="absolute"					, UpperCAmelCase_       :	List[str]=True					, UpperCAmelCase_       :	Dict=False					, UpperCAmelCase_       :	List[Any]=101					, UpperCAmelCase_       :	Optional[Any]=102					, UpperCAmelCase_       :	List[str]=None					, **UpperCAmelCase_       :	Tuple					, ):
       super().__init__(bos_token_id=_lowerCamelCase					, eos_token_id=_lowerCamelCase					, pad_token_id=_lowerCamelCase					, **_lowerCamelCase      )

       if vision_config is None:
         SCREAMING_SNAKE_CASE       :      Any							=    {}
         logger.info("vision_config is None. initializing the GitVisionConfig with default values."      )

       SCREAMING_SNAKE_CASE       :      Any							=    GitVisionConfig(**_lowerCamelCase      )
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    vocab_size
       SCREAMING_SNAKE_CASE       :      List[Any]							=    hidden_size
       SCREAMING_SNAKE_CASE       :      Any							=    num_hidden_layers
       SCREAMING_SNAKE_CASE       :      Tuple							=    num_attention_heads
       SCREAMING_SNAKE_CASE       :      Tuple							=    hidden_act
       SCREAMING_SNAKE_CASE       :      int							=    intermediate_size
       SCREAMING_SNAKE_CASE       :      List[str]							=    hidden_dropout_prob
       SCREAMING_SNAKE_CASE       :      List[str]							=    attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE       :      Dict							=    max_position_embeddings
       SCREAMING_SNAKE_CASE       :      List[Any]							=    initializer_range
       SCREAMING_SNAKE_CASE       :      Any							=    layer_norm_eps
       SCREAMING_SNAKE_CASE       :      str							=    position_embedding_type
       SCREAMING_SNAKE_CASE       :      int							=    use_cache
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    tie_word_embeddings
       SCREAMING_SNAKE_CASE       :      int							=    num_image_with_embedding

       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    bos_token_id
       SCREAMING_SNAKE_CASE       :      List[Any]							=    eos_token_id






     def 				_A       (				self       :	Optional[int]      ):
       SCREAMING_SNAKE_CASE       :      Tuple							=    copy.deepcopy(self.__dict__      )
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    self.vision_config.to_dict()
       SCREAMING_SNAKE_CASE       :      List[str]							=    self.__class__.model_type
       return output














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






