



import argparse
import os
import re

import packaging.version


a_						:     Tuple	     =		'examples/'
a_						:     str	     =		{
    'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
    'init': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
    'setup': (re.compile(R'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), R'\1version="VERSION",'),
    'doc': (re.compile(R'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
}
a_						:     Tuple	     =		{
    'init': 'src/diffusers/__init__.py',
    'setup': 'setup.py',
}
a_						:     Optional[Any]	     =		'README.md'

def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ ):


      """simple docstring"""



      with open(UpperCAmelCase__   ,   "r"   ,   encoding="utf-8"   ,   newline="\n" ) as f:
            lowerCamelCase								=		f.read()
      lowerCamelCase			,							lowerCamelCase								=		REPLACE_PATTERNS[pattern]
      lowerCamelCase								=		replace.replace("VERSION"   ,   UpperCAmelCase__ )
      lowerCamelCase								=		re_pattern.sub(UpperCAmelCase__   ,   UpperCAmelCase__ )
      with open(UpperCAmelCase__   ,   "w"   ,   encoding="utf-8"   ,   newline="\n" ) as f:
            f.write(UpperCAmelCase__ )

def     __lowercase(	UpperCAmelCase__ ):


      """simple docstring"""



      for folder, directories, fnames in os.walk(UpperCAmelCase__ ):
            # Removing some of the folders with non-actively maintained examples from the walk
            if "research_projects" in directories:
                  directories.remove("research_projects" )
            if "legacy" in directories:
                  directories.remove("legacy" )
            for fname in fnames:
                  if fname.endswith(".py" ):
                        update_version_in_file(os.path.join(UpperCAmelCase__   ,   UpperCAmelCase__ )   ,   UpperCAmelCase__   ,   pattern="examples" )

def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__=False ):


      """simple docstring"""



      for pattern, fname in REPLACE_FILES.items():
            update_version_in_file(UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ )
      if not patch:
            update_version_in_examples(UpperCAmelCase__ )

def     __lowercase(	):


      """simple docstring"""



      lowerCamelCase								=		"🤗 Transformers currently provides the following architectures"
      lowerCamelCase								=		"1. Want to contribute a new model?"
      with open(UpperCAmelCase__   ,   "r"   ,   encoding="utf-8"   ,   newline="\n" ) as f:
            lowerCamelCase								=		f.readlines()

      # Find the start of the list.
      lowerCamelCase								=		0
      while not lines[start_index].startswith(_start_prompt ):
            start_index += 1
      start_index += 1

      lowerCamelCase								=		start_index
      # Update the lines in the model list.
      while not lines[index].startswith(_end_prompt ):
            if lines[index].startswith("1." ):
                  lowerCamelCase								=		lines[index].replace(
                      "https://huggingface.co/docs/diffusers/main/model_doc"   ,   "https://huggingface.co/docs/diffusers/model_doc"   ,   )
            index += 1

      with open(UpperCAmelCase__   ,   "w"   ,   encoding="utf-8"   ,   newline="\n" ) as f:
            f.writelines(UpperCAmelCase__ )

def     __lowercase(	):


      """simple docstring"""



      with open(REPLACE_FILES["init"]   ,   "r" ) as f:
            lowerCamelCase								=		f.read()
      lowerCamelCase								=		REPLACE_PATTERNS["init"][0].search(UpperCAmelCase__ ).groups()[0]
      return packaging.version.parse(UpperCAmelCase__ )

def     __lowercase(	UpperCAmelCase__=False ):


      """simple docstring"""



      lowerCamelCase								=		get_version()
      if patch and default_version.is_devrelease:
            raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" )
      if default_version.is_devrelease:
            lowerCamelCase								=		default_version.base_version
      elif patch:
            lowerCamelCase								=		F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
      else:
            lowerCamelCase								=		F"""{default_version.major}.{default_version.minor + 1}.0"""

      # Now let's ask nicely if that's the right one.
      lowerCamelCase								=		input(F"""Which version are you releasing? [{default_version}]""" )
      if len(UpperCAmelCase__ ) == 0:
            lowerCamelCase								=		default_version

      print(F"""Updating version to {version}.""" )
      global_version_update(UpperCAmelCase__   ,   patch=UpperCAmelCase__ )

def     __lowercase(	):


      """simple docstring"""



      lowerCamelCase								=		get_version()
      lowerCamelCase								=		F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
      lowerCamelCase								=		current_version.base_version

      # Check with the user we got that right.
      lowerCamelCase								=		input(F"""Which version are we developing now? [{dev_version}]""" )
      if len(UpperCAmelCase__ ) == 0:
            lowerCamelCase								=		dev_version

      print(F"""Updating version to {version}.""" )
      global_version_update(UpperCAmelCase__ )


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
     a_						:     Optional[Any]	     =		argparse.ArgumentParser()
     parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.')
     parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.')
     a_						:     Any	     =		parser.parse_args()
     if not args.post_release:
          pre_release_work(patch=args.patch)
     elif args.patch:
          print('Nothing to do after a patch :-)')
     else:
          post_release_work()




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

from ...utils import logging


a_						:     Tuple	     =		logging.get_logger(__name__)





class    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     _A       =			CLIPConfig

     _A       =			['CLIPEncoderLayer']







     def __init__(self				,			__a    ):






           '''simple docstring'''



           super().__init__(__a    )

           lowerCamelCase								=		CLIPVisionModelWithProjection(config.vision_config    )

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







     @torch.no_grad()
     def 						_a      (self				,			__a				,			__a				,			__a=0.5				,			__a=0.5    ):






           '''simple docstring'''



           lowerCamelCase								=		self.vision_model(__a    )[0]

           lowerCamelCase								=		self.p_head(__a    )
           lowerCamelCase								=		nsfw_detected.flatten()
           lowerCamelCase								=		nsfw_detected > p_threshold
           lowerCamelCase								=		nsfw_detected.tolist()

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

           lowerCamelCase								=		self.w_head(__a    )
           lowerCamelCase								=		watermark_detected.flatten()
           lowerCamelCase								=		watermark_detected > w_threshold
           lowerCamelCase								=		watermark_detected.tolist()

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

           return images, nsfw_detected, watermark_detected