





import argparse
import os
import re

import packaging.version


snake_case								=							"""examples/"""
snake_case								=							{
    """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"""),
}
snake_case								=							{
    """init""": """src/diffusers/__init__.py""",
    """setup""": """setup.py""",
}
snake_case								=							"""README.md"""

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:Optional[int]      ,				snake_case__	:Any      ,				snake_case__	:Optional[int]  )   ->    Tuple:
  with open(snake_case__      ,				'r'      ,				encoding='utf-8'      ,				newline='\n'  ) as f:
    _lowercase						    =			f.read()
  _lowercase    ,		_lowercase						    =			REPLACE_PATTERNS[pattern]
  _lowercase						    =			replace.replace('VERSION'      ,				snake_case__  )
  _lowercase						    =			re_pattern.sub(snake_case__      ,				snake_case__  )
  with open(snake_case__      ,				'w'      ,				encoding='utf-8'      ,				newline='\n'  ) as f:
    f.write(snake_case__  )

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:Dict  )   ->    Optional[Any]:
  for folder, directories, fnames in os.walk(snake_case__  ):
    # 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(snake_case__      ,				snake_case__  )      ,				snake_case__      ,				pattern='examples'  )

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:Any      ,				snake_case__	:Tuple=False  )   ->    List[Any]:
  for pattern, fname in REPLACE_FILES.items():
    update_version_in_file(snake_case__      ,				snake_case__      ,				snake_case__  )
  if not patch:
    update_version_in_examples(snake_case__  )

def 				SCREAMING_SNAKE_CASE__							(	)   ->    int:
  _lowercase						    =			'🤗 Transformers currently provides the following architectures'
  _lowercase						    =			'1. Want to contribute a new model?'
  with open(snake_case__      ,				'r'      ,				encoding='utf-8'      ,				newline='\n'  ) as f:
    _lowercase						    =			f.readlines()

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

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

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

def 				SCREAMING_SNAKE_CASE__							(	)   ->    Optional[Any]:
  with open(REPLACE_FILES['init']      ,				'r'  ) as f:
    _lowercase						    =			f.read()
  _lowercase						    =			REPLACE_PATTERNS['init'][0].search(snake_case__  ).groups()[0]
  return packaging.version.parse(snake_case__  )

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:Tuple=False  )   ->    Tuple:
  _lowercase						    =			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:
    _lowercase						    =			default_version.base_version
  elif patch:
    _lowercase						    =			F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
  else:
    _lowercase						    =			F"""{default_version.major}.{default_version.minor + 1}.0"""

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

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

def 				SCREAMING_SNAKE_CASE__							(	)   ->    Any:
  _lowercase						    =			get_version()
  _lowercase						    =			F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
  _lowercase						    =			current_version.base_version

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

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


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


if __name__ == "__main__":
      snake_case								=							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.""")
      snake_case								=							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()







from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


lowercase    				=   "CompVis/stable-diffusion-v1-1"
lowercase    				=   "CompVis/stable-diffusion-v1-2"
lowercase    				=   "CompVis/stable-diffusion-v1-3"
lowercase    				=   "CompVis/stable-diffusion-v1-4"




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	def __init__(			self			,     a			,     a			,     a			,     a			,     a			,     a			,     a			,     a = True			,     )			->       int:
								super()._init_()

								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline(
								    vae=a			,     text_encoder=a			,     tokenizer=a			,     unet=a			,     scheduler=a			,     safety_checker=a			,     feature_extractor=a			,     requires_safety_checker=a			,     )

								self.register_modules(pipelinea=self.pipea			,     pipelinea=self.pipea			,     pipelinea=self.pipea			,     pipelinea=self.pipea   )




	@property
	def 				_UpperCamelCase     (			self   )			->       Dict[str, Any]:
								return {k: getattr(self			,     a   ) for k in self.config.keys() if not k.startswith('_'   )}




	def 				_UpperCamelCase     (			self			,     a = "auto"   )			->       Dict:
								if slice_size == "auto":
															# half the attention head size is usually a good trade-off between
															# speed and memory
															snake_case_           =				self.unet.config.attention_head_dim // 2
								self.unet.set_attention_slice(a   )




	def 				_UpperCamelCase     (			self   )			->       List[Any]:
								self.enable_attention_slicing(a   )




	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       Optional[Any]:
								return self.pipea(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )




	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       int:
								return self.pipea(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )




	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       Optional[int]:
								return self.pipea(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )




	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       Any:
								return self.pipea(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )






	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       Optional[Any]:
								snake_case_           =				'cuda' if torch.cuda.is_available() else 'cpu'
								self.to(a   )

								# Checks if the height and width are divisible by 8 or not
								if height % 8 != 0 or width % 8 != 0:
															raise ValueError(F'''`height` and `width` must be divisible by 8 but are {height} and {width}.'''   )

								# Get first result from Stable Diffusion Checkpoint v1.1
								snake_case_           =				self.textaimg_sda_a(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )

								# Get first result from Stable Diffusion Checkpoint v1.2
								snake_case_           =				self.textaimg_sda_a(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )

								# Get first result from Stable Diffusion Checkpoint v1.3
								snake_case_           =				self.textaimg_sda_a(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )

								# Get first result from Stable Diffusion Checkpoint v1.4
								snake_case_           =				self.textaimg_sda_a(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )

								# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
								return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]   )





