

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

from ...utils import logging


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

class    _a (       lowerCAmelCase_							):




      """simple docstring"""

      _lowerCamelCase    :       Optional[Any]							=    CLIPConfig

      _lowerCamelCase    :       Optional[Any]							=    ["""CLIPEncoderLayer"""]





      def __init__(					self				:							Dict		,       UpperCAmelCase				:							CLIPConfig     ):
            super().__init__(snake_case_     )

            A_		   =							CLIPVisionModelWithProjection(config.vision_config     )

            A_		   =							nn.Linear(config.vision_config.projection_dim		,       1     )
            A_		   =							nn.Linear(config.vision_config.projection_dim		,       1     )







      @torch.no_grad()
      def 						__A     (					self				:							List[Any]		,       UpperCAmelCase				:							Optional[int]		,       UpperCAmelCase				:							Union[str, Any]		,       UpperCAmelCase				:							Optional[int]=0.5		,       UpperCAmelCase				:							List[str]=0.5     ):
            A_		   =							self.vision_model(snake_case_     )[0]

            A_		   =							self.p_head(snake_case_     )
            A_		   =							nsfw_detected.flatten()
            A_		   =							nsfw_detected > p_threshold
            A_		   =							nsfw_detected.tolist()

            if any(snake_case_     ):
                  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(snake_case_     ):
                  if nsfw_detected_:
                        A_		   =							np.zeros(images[idx].shape     )

            A_		   =							self.w_head(snake_case_     )
            A_		   =							watermark_detected.flatten()
            A_		   =							watermark_detected > w_threshold
            A_		   =							watermark_detected.tolist()

            if any(snake_case_     ):
                  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(snake_case_     ):
                  if watermark_detected_:
                        A_		   =							np.zeros(images[idx].shape     )

            return images, nsfw_detected, watermark_detected






'''simple docstring'''




import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
  from .tokenization_albert import AlbertTokenizer
else:
  __SCREAMING_SNAKE_CASE     :List[Any]       =				None

__SCREAMING_SNAKE_CASE     :Union[str, Any]       =				logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE     :List[str]       =				{'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''}

__SCREAMING_SNAKE_CASE     :List[Any]       =				{
    '''vocab_file''': {
        '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''',
        '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''',
        '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''',
        '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''',
        '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''',
        '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''',
        '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''',
        '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''',
    },
    '''tokenizer_file''': {
        '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json''',
        '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json''',
        '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json''',
        '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json''',
        '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json''',
        '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json''',
        '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json''',
        '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json''',
    },
}

__SCREAMING_SNAKE_CASE     :Optional[Any]       =				{
    '''albert-base-v1''': 512,
    '''albert-large-v1''': 512,
    '''albert-xlarge-v1''': 512,
    '''albert-xxlarge-v1''': 512,
    '''albert-base-v2''': 512,
    '''albert-large-v2''': 512,
    '''albert-xlarge-v2''': 512,
    '''albert-xxlarge-v2''': 512,
}

__SCREAMING_SNAKE_CASE     :Optional[int]       =				'''▁'''







class   A_	(  lowerCAmelCase_			):
 _lowerCamelCase  : Optional[int]           =							VOCAB_FILES_NAMES
 _lowerCamelCase  : Any           =							PRETRAINED_VOCAB_FILES_MAP
 _lowerCamelCase  : Tuple           =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowerCamelCase  : int           =							AlbertTokenizer




 def __init__(					self       :    Optional[Any]	,			snake_case_       :    Optional[Any]=None	,			snake_case_       :    Optional[Any]=None	,			snake_case_       :    Optional[Any]=True	,			snake_case_       :    str=True	,			snake_case_       :    Tuple=False	,			snake_case_       :    List[Any]="[CLS]"	,			snake_case_       :    Union[str, Any]="[SEP]"	,			snake_case_       :    str="<unk>"	,			snake_case_       :    Union[str, Any]="[SEP]"	,			snake_case_       :    List[Any]="<pad>"	,			snake_case_       :    List[str]="[CLS]"	,			snake_case_       :    int="[MASK]"	,			**snake_case_       :    Any	,			):
      # Mask token behave like a normal word, i.e. include the space before it and
      # is included in the raw text, there should be a match in a non-normalized sentence.
      _UpperCAmelCase     							=   (
          AddedToken(snake_case_	,			lstrip=snake_case_	,			rstrip=snake_case_	,			normalized=snake_case_    )
          if isinstance(snake_case_	,			snake_case_    )
          else mask_token
      )

      super().__init__(
          snake_case_	,			tokenizer_file=snake_case_	,			do_lower_case=snake_case_	,			remove_space=snake_case_	,			keep_accents=snake_case_	,			bos_token=snake_case_	,			eos_token=snake_case_	,			unk_token=snake_case_	,			sep_token=snake_case_	,			pad_token=snake_case_	,			cls_token=snake_case_	,			mask_token=snake_case_	,			**snake_case_	,			)

      _UpperCAmelCase     							=   do_lower_case
      _UpperCAmelCase     							=   remove_space
      _UpperCAmelCase     							=   keep_accents
      _UpperCAmelCase     							=   vocab_file
      _UpperCAmelCase     							=   False if not self.vocab_file else True




 def      lowercase	(					self       :    Union[str, Any]	,			snake_case_       :    List[int]	,			snake_case_       :    Optional[List[int]] = None    ):
      _UpperCAmelCase     							=   [self.sep_token_id]
      _UpperCAmelCase     							=   [self.cls_token_id]
      if token_ids_a is None:
           return cls + token_ids_a + sep
      return cls + token_ids_a + sep + token_ids_a + sep




 def      lowercase	(					self       :    Dict	,			snake_case_       :    List[int]	,			snake_case_       :    Optional[List[int]] = None    ):
      _UpperCAmelCase     							=   [self.sep_token_id]
      _UpperCAmelCase     							=   [self.cls_token_id]

      if token_ids_a is None:
           return len(cls + token_ids_a + sep    ) * [0]
      return len(cls + token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1]




 def      lowercase	(					self       :    Optional[Any]	,			snake_case_       :    str	,			snake_case_       :    Optional[str] = None    ):
      if not self.can_save_slow_tokenizer:
           raise ValueError(
               "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
               "tokenizer."    )

      if not os.path.isdir(snake_case_    ):
           logger.error(f'Vocabulary path ({save_directory}) should be a directory'    )
           return
      _UpperCAmelCase     							=   os.path.join(
          snake_case_	,			(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]    )

      if os.path.abspath(self.vocab_file    ) != os.path.abspath(snake_case_    ):
           copyfile(self.vocab_file	,			snake_case_    )

      return (out_vocab_file,)




