




'''simple docstring'''






import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
				import torch

				_lowerCAmelCase				     = True
except ImportError:
				_lowerCAmelCase				     = False


try:
				from torch.hub import _get_torch_home

				_lowerCAmelCase				     = _get_torch_home()
except ImportError:
				_lowerCAmelCase				     = os.path.expanduser(
				    os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
				)

_lowerCAmelCase				     = os.path.join(torch_cache_home, '''transformers''')

_lowerCAmelCase				     = '''https://cdn.huggingface.co'''
_lowerCAmelCase				     = '''https://s3.amazonaws.com/models.huggingface.co/bert'''
_lowerCAmelCase				     = '''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1])
_lowerCAmelCase				     = os.path.join(PATH, '''config.yaml''')
_lowerCAmelCase				     = os.path.join(PATH, '''attributes.txt''')
_lowerCAmelCase				     = os.path.join(PATH, '''objects.txt''')
_lowerCAmelCase				     = os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path)
_lowerCAmelCase				     = os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE)
_lowerCAmelCase				     = os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE)
_lowerCAmelCase				     = '''pytorch_model.bin'''
_lowerCAmelCase				     = '''config.yaml'''

def       __lowerCAmelCase (   snake_case__=OBJECTS ,				snake_case__=ATTRIBUTES						):
			__UpperCamelCase				:      Optional[int]									=       []
			with open(snake_case__						) as f:
						for object in f.readlines():
									vg_classes.append(object.split(","						)[0].lower().strip()						)

			__UpperCamelCase				:      List[Any]									=       []
			with open(snake_case__						) as f:
						for object in f.readlines():
									vg_attrs.append(object.split(","						)[0].lower().strip()						)
			return vg_classes, vg_attrs

def       __lowerCAmelCase (   snake_case__						):
			__UpperCamelCase				:      Optional[Any]									=       OrderedDict()
			with open(snake_case__ ,				"rb"						) as f:
						__UpperCamelCase				:      Union[str, Any]									=       pkl.load(snake_case__						)["model"]
			for k in copy.deepcopy(list(ckp.keys()						)						):
						__UpperCamelCase				:      str									=       ckp.pop(snake_case__						)
						if isinstance(snake_case__ ,				np.ndarray						):
									__UpperCamelCase				:      Any									=       torch.tensor(snake_case__						)
						else:
									assert isinstance(snake_case__ ,				torch.tensor						), type(snake_case__						)
						__UpperCamelCase				:      Optional[Any]									=       v
			return r



class  A		:




				'''simple docstring'''





				A				     =    {}
				def __init__(self			,  _UpperCAmelCase			,  _UpperCAmelCase = "root"			,  _UpperCAmelCase=0      )     ->	Optional[int]:
							__UpperCamelCase				:      Dict									=       name
							__UpperCamelCase				:      Dict									=       level
							__UpperCamelCase				:      List[str]									=       {}
							for k, v in dictionary.items():
										if v is None:
													raise ValueError()
										__UpperCamelCase				:      str									=       copy.deepcopy(_UpperCAmelCase      )
										__UpperCamelCase				:      Union[str, Any]									=       copy.deepcopy(_UpperCAmelCase      )
										if isinstance(_UpperCAmelCase			,  _UpperCAmelCase      ):
													__UpperCamelCase				:      Optional[Any]									=       Config(_UpperCAmelCase			,  name=_UpperCAmelCase			,  level=level + 1      )
										__UpperCamelCase				:      str									=       v
										setattr(self			,  _UpperCAmelCase			,  _UpperCAmelCase      )

							__UpperCamelCase				:      List[str]									=       d
				def __repr__(self      )     ->	Tuple:
							return str(list((self._pointer.keys())      )      )
				def __setattr__(self			,  _UpperCAmelCase			,  _UpperCAmelCase      )     ->	str:
							__UpperCamelCase				:      Any									=       val
							__UpperCamelCase				:      Union[str, Any]									=       val
							__UpperCamelCase				:      List[Any]									=       key.split("."      )
							__UpperCamelCase				:      Any									=       len(_UpperCAmelCase      ) - 1
							__UpperCamelCase				:      Any									=       self._pointer
							if len(_UpperCAmelCase      ) > 1:
										for i, l in enumerate(_UpperCAmelCase      ):
													if hasattr(self			,  _UpperCAmelCase      ) and isinstance(getattr(self			,  _UpperCAmelCase      )			,  _UpperCAmelCase      ):
																setattr(getattr(self			,  _UpperCAmelCase      )			,  ".".join(levels[i:]      )			,  _UpperCAmelCase      )
													if l == last_level:
																__UpperCamelCase				:      List[Any]									=       val
													else:
																__UpperCamelCase				:      List[Any]									=       pointer[l]
				def 	a_	(self      )     ->	int:
							return self._pointer
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase      )     ->	str:
							with open(f"{file_name}"			,  "w"      ) as stream:
										dump(_UpperCAmelCase			,  _UpperCAmelCase      )
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase      )     ->	List[str]:
							with open(f"{file_name}"			,  "w"      ) as stream:
										json.dump(_UpperCAmelCase			,  _UpperCAmelCase      )
				@staticmethod
				def 	a_	(_UpperCAmelCase      )     ->	Optional[int]:
							with open(_UpperCAmelCase      ) as stream:
										__UpperCamelCase				:      str									=       load(_UpperCAmelCase			,  Loader=_UpperCAmelCase      )
							return data
				def __str__(self      )     ->	int:
							__UpperCamelCase				:      Union[str, Any]									=       "    "
							if self._name != "root":
										__UpperCamelCase				:      List[str]									=       f"{t * (self._level-1)}{self._name}:\n"
							else:
										__UpperCamelCase				:      Tuple									=       ""
							__UpperCamelCase				:      List[Any]									=       self._level
							for i, (k, v) in enumerate(self._pointer.items()      ):
										if isinstance(_UpperCAmelCase			,  _UpperCAmelCase      ):
													r += f"{t * (self._level)}{v}\n"
													self._level += 1
										else:
													r += f"{t * (self._level)}{k}: {v} ({type(_UpperCAmelCase      ).__name__})\n"
										__UpperCamelCase				:      str									=       level
							return r[:-1]
				@classmethod
				def 	a_	(cls			,  _UpperCAmelCase			,  **_UpperCAmelCase      )     ->	List[str]:
							__UpperCamelCase		, __UpperCamelCase				:      List[Any]									=       cls.get_config_dict(_UpperCAmelCase			,  **_UpperCAmelCase      )
							return cls(_UpperCAmelCase      )





				@classmethod
				def 	a_	(cls			,  _UpperCAmelCase			,  **_UpperCAmelCase      )     ->	Optional[Any]:
							__UpperCamelCase				:      List[str]									=       kwargs.pop("cache_dir"			,  _UpperCAmelCase      )
							__UpperCamelCase				:      str									=       kwargs.pop("force_download"			,  _UpperCAmelCase      )
							__UpperCamelCase				:      List[str]									=       kwargs.pop("resume_download"			,  _UpperCAmelCase      )
							__UpperCamelCase				:      int									=       kwargs.pop("proxies"			,  _UpperCAmelCase      )
							__UpperCamelCase				:      str									=       kwargs.pop("local_files_only"			,  _UpperCAmelCase      )

							if os.path.isdir(_UpperCAmelCase      ):
										__UpperCamelCase				:      List[str]									=       os.path.join(_UpperCAmelCase			,  _UpperCAmelCase      )
							elif os.path.isfile(_UpperCAmelCase      ) or is_remote_url(_UpperCAmelCase      ):
										__UpperCamelCase				:      Optional[Any]									=       pretrained_model_name_or_path
							else:
										__UpperCamelCase				:      Optional[Any]									=       hf_bucket_url(_UpperCAmelCase			,  filename=_UpperCAmelCase			,  use_cdn=_UpperCAmelCase      )

							try:
										# Load from URL or cache if already cached
										__UpperCamelCase				:      str									=       cached_path(
										    _UpperCAmelCase			,  cache_dir=_UpperCAmelCase			,  force_download=_UpperCAmelCase			,  proxies=_UpperCAmelCase			,  resume_download=_UpperCAmelCase			,  local_files_only=_UpperCAmelCase			,  )
										# Load config dict
										if resolved_config_file is None:
													raise EnvironmentError

										__UpperCamelCase				:      Tuple									=       Config.load_yaml(_UpperCAmelCase      )

							except EnvironmentError:
										__UpperCamelCase				:      int									=       "Can't load config for"
										raise EnvironmentError(_UpperCAmelCase      )

							if resolved_config_file == config_file:
										print("loading configuration file from path"      )
							else:
										print("loading configuration file cache"      )

							return Config.load_yaml(_UpperCAmelCase      ), kwargs







def       __lowerCAmelCase (   snake_case__						):
			__UpperCamelCase				:      List[str]									=       torch.load("dump.pt" ,				map_location=in_tensor.device						)
			__UpperCamelCase				:      Tuple									=       in_tensor.numpy()
			__UpperCamelCase				:      Union[str, Any]									=       out_tensor.numpy()[0]
			print(na.shape ,				na[0, 0, :5]						)
			print(na.shape ,				na[0, 0, :5]						)
			assert np.allclose(snake_case__ ,				snake_case__ ,				rtol=0.01 ,				atol=0.1						), (
			    F"{sum([1 for x in np.isclose(snake_case__ ,				snake_case__ ,				rtol=0.01 ,				atol=0.1						).flatten() if x is False]						)/len(na.flatten()						)*100:.4f} %"
			    " element-wise mismatch"
			)
			raise Exception("tensors are all good"						)

			# Hugging face functions below

def       __lowerCAmelCase (   snake_case__						):
			__UpperCamelCase				:      List[Any]									=       urlparse(snake_case__						)
			return parsed.scheme in ("http", "https")

def       __lowerCAmelCase (   snake_case__ ,				snake_case__ ,				snake_case__=True						):
			__UpperCamelCase				:      Tuple									=       CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
			__UpperCamelCase				:      Tuple									=       "/" not in model_id
			if legacy_format:
						return F"{endpoint}/{model_id}-{filename}"
			else:
						return F"{endpoint}/{model_id}/{filename}"

def       __lowerCAmelCase (   snake_case__ ,				snake_case__ ,				snake_case__=None ,				snake_case__=0 ,				snake_case__=None ,				):
			__UpperCamelCase				:      Any									=       "python/{}".format(sys.version.split()[0]						)
			if _torch_available:
						ua += "; torch/{}".format(torch.__version__						)
			if isinstance(snake_case__ ,				snake_case__						):
						ua += "; " + "; ".join("{}/{}".format(snake_case__ ,				snake_case__						) for k, v in user_agent.items()						)
			elif isinstance(snake_case__ ,				snake_case__						):
						ua += "; " + user_agent
			__UpperCamelCase				:      Optional[int]									=       {"user-agent": ua}
			if resume_size > 0:
						__UpperCamelCase				:      int									=       "bytes=%d-" % (resume_size,)
			__UpperCamelCase				:      Dict									=       requests.get(snake_case__ ,				stream=snake_case__ ,				proxies=snake_case__ ,				headers=snake_case__						)
			if response.status_code == 416:  # Range not satisfiable
						return
			__UpperCamelCase				:      Dict									=       response.headers.get("Content-Length"						)
			__UpperCamelCase				:      Tuple									=       resume_size + int(snake_case__						) if content_length is not None else None
			__UpperCamelCase				:      Optional[Any]									=       tqdm(
			    unit="B" ,				unit_scale=snake_case__ ,				total=snake_case__ ,				initial=snake_case__ ,				desc="Downloading" ,				)
			for chunk in response.iter_content(chunk_size=1_024						):
						if chunk:  # filter out keep-alive new chunks
									progress.update(len(snake_case__						)						)
									temp_file.write(snake_case__						)
			progress.close()

def       __lowerCAmelCase (   snake_case__ ,				snake_case__=None ,				snake_case__=False ,				snake_case__=None ,				snake_case__=10 ,				snake_case__=False ,				snake_case__=None ,				snake_case__=False ,				):
			if cache_dir is None:
						__UpperCamelCase				:      Optional[int]									=       TRANSFORMERS_CACHE
			if isinstance(snake_case__ ,				snake_case__						):
						__UpperCamelCase				:      Tuple									=       str(snake_case__						)

			os.makedirs(snake_case__ ,				exist_ok=snake_case__						)

			__UpperCamelCase				:      Dict									=       None
			if not local_files_only:
						try:
									__UpperCamelCase				:      Dict									=       requests.head(snake_case__ ,				allow_redirects=snake_case__ ,				proxies=snake_case__ ,				timeout=snake_case__						)
									if response.status_code == 200:
												__UpperCamelCase				:      List[str]									=       response.headers.get("ETag"						)
						except (EnvironmentError, requests.exceptions.Timeout):
									# etag is already None
									pass

			__UpperCamelCase				:      List[str]									=       url_to_filename(snake_case__ ,				snake_case__						)

			# get cache path to put the file
			__UpperCamelCase				:      Union[str, Any]									=       os.path.join(snake_case__ ,				snake_case__						)

			# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
			# try to get the last downloaded one
			if etag is None:
						if os.path.exists(snake_case__						):
									return cache_path
						else:
									__UpperCamelCase				:      Union[str, Any]									=       [
									    file
									    for file in fnmatch.filter(os.listdir(snake_case__						) ,				filename + ".*"						)
									    if not file.endswith(".json"						) and not file.endswith(".lock"						)
									]
									if len(snake_case__						) > 0:
												return os.path.join(snake_case__ ,				matching_files[-1]						)
									else:
												# If files cannot be found and local_files_only=True,
												# the models might've been found if local_files_only=False
												# Notify the user about that
												if local_files_only:
															raise ValueError(
															    "Cannot find the requested files in the cached path and outgoing traffic has been"
															    " disabled. To enable model look-ups and downloads online, set 'local_files_only'"
															    " to False."						)
												return None

    # From now on, etag is not None.
			if os.path.exists(snake_case__						) and not force_download:
						return cache_path

			# Prevent parallel downloads of the same file with a lock.
			__UpperCamelCase				:      str									=       cache_path + ".lock"
			with FileLock(snake_case__						):
						# If the download just completed while the lock was activated.
						if os.path.exists(snake_case__						) and not force_download:
									# Even if returning early like here, the lock will be released.
									return cache_path

						if resume_download:
									__UpperCamelCase				:      Tuple									=       cache_path + ".incomplete"

									@contextmanager
									def _resumable_file_manager():
												with open(snake_case__ ,				"a+b"						) as f:
															yield f

									__UpperCamelCase				:      List[str]									=       _resumable_file_manager
									if os.path.exists(snake_case__						):
												__UpperCamelCase				:      List[Any]									=       os.stat(snake_case__						).st_size
									else:
												__UpperCamelCase				:      List[Any]									=       0
						else:
									__UpperCamelCase				:      Any									=       partial(tempfile.NamedTemporaryFile ,				dir=snake_case__ ,				delete=snake_case__						)
									__UpperCamelCase				:      Optional[Any]									=       0

						# Download to temporary file, then copy to cache dir once finished.
						# Otherwise you get corrupt cache entries if the download gets interrupted.
						with temp_file_manager() as temp_file:
									print(
									    "%s not found in cache or force_download set to True, downloading to %s" ,				snake_case__ ,				temp_file.name ,				)

									http_get(
									    snake_case__ ,				snake_case__ ,				proxies=snake_case__ ,				resume_size=snake_case__ ,				user_agent=snake_case__ ,				)

						os.replace(temp_file.name ,				snake_case__						)

						__UpperCamelCase				:      Dict									=       {"url": url, "etag": etag}
						__UpperCamelCase				:      Dict									=       cache_path + ".json"
						with open(snake_case__ ,				"w"						) as meta_file:
									json.dump(snake_case__ ,				snake_case__						)

			return cache_path

def       __lowerCAmelCase (   snake_case__ ,				snake_case__=None						):
			__UpperCamelCase				:      int									=       url.encode("utf-8"						)
			__UpperCamelCase				:      Tuple									=       shaaaa(snake_case__						)
			__UpperCamelCase				:      Tuple									=       url_hash.hexdigest()

			if etag:
						__UpperCamelCase				:      List[Any]									=       etag.encode("utf-8"						)
						__UpperCamelCase				:      List[Any]									=       shaaaa(snake_case__						)
						filename += "." + etag_hash.hexdigest()

			if url.endswith(".h5"						):
						filename += ".h5"

			return filename

def       __lowerCAmelCase (   snake_case__ ,				snake_case__=None ,				snake_case__=False ,				snake_case__=None ,				snake_case__=False ,				snake_case__=None ,				snake_case__=False ,				snake_case__=False ,				snake_case__=False ,				):
			if cache_dir is None:
						__UpperCamelCase				:      int									=       TRANSFORMERS_CACHE
			if isinstance(snake_case__ ,				snake_case__						):
						__UpperCamelCase				:      Optional[int]									=       str(snake_case__						)
			if isinstance(snake_case__ ,				snake_case__						):
						__UpperCamelCase				:      List[Any]									=       str(snake_case__						)

			if is_remote_url(snake_case__						):
						# URL, so get it from the cache (downloading if necessary)
						__UpperCamelCase				:      Tuple									=       get_from_cache(
						    snake_case__ ,				cache_dir=snake_case__ ,				force_download=snake_case__ ,				proxies=snake_case__ ,				resume_download=snake_case__ ,				user_agent=snake_case__ ,				local_files_only=snake_case__ ,				)
			elif os.path.exists(snake_case__						):
						# File, and it exists.
						__UpperCamelCase				:      int									=       url_or_filename
			elif urlparse(snake_case__						).scheme == "":
						# File, but it doesn't exist.
						raise EnvironmentError("file {} not found".format(snake_case__						)						)
			else:
						# Something unknown
						raise ValueError("unable to parse {} as a URL or as a local path".format(snake_case__						)						)

			if extract_compressed_file:
						if not is_zipfile(snake_case__						) and not tarfile.is_tarfile(snake_case__						):
									return output_path

						# Path where we extract compressed archives
						# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
						__UpperCamelCase		, __UpperCamelCase				:      Optional[Any]									=       os.path.split(snake_case__						)
						__UpperCamelCase				:      Any									=       output_file.replace("." ,				"-"						) + "-extracted"
						__UpperCamelCase				:      List[Any]									=       os.path.join(snake_case__ ,				snake_case__						)

						if os.path.isdir(snake_case__						) and os.listdir(snake_case__						) and not force_extract:
									return output_path_extracted

						# Prevent parallel extractions
						__UpperCamelCase				:      int									=       output_path + ".lock"
						with FileLock(snake_case__						):
									shutil.rmtree(snake_case__ ,				ignore_errors=snake_case__						)
									os.makedirs(snake_case__						)
									if is_zipfile(snake_case__						):
												with ZipFile(snake_case__ ,				"r"						) as zip_file:
															zip_file.extractall(snake_case__						)
															zip_file.close()
									elif tarfile.is_tarfile(snake_case__						):
												__UpperCamelCase				:      Tuple									=       tarfile.open(snake_case__						)
												tar_file.extractall(snake_case__						)
												tar_file.close()
									else:
												raise EnvironmentError("Archive format of {} could not be identified".format(snake_case__						)						)

						return output_path_extracted

			return output_path

def       __lowerCAmelCase (   snake_case__ ,				snake_case__=","						):
			assert isinstance(snake_case__ ,				snake_case__						)
			if os.path.isfile(snake_case__						):
						with open(snake_case__						) as f:
									__UpperCamelCase				:      Optional[int]									=       eval(f.read()						)
			else:
						__UpperCamelCase				:      List[str]									=       requests.get(snake_case__						)
						try:
									__UpperCamelCase				:      Any									=       requests.json()
						except Exception:
									__UpperCamelCase				:      Tuple									=       req.content.decode()
									assert data is not None, "could not connect"
									try:
												__UpperCamelCase				:      Optional[int]									=       eval(snake_case__						)
									except Exception:
												__UpperCamelCase				:      Union[str, Any]									=       data.split("\n"						)
						req.close()
			return data

def       __lowerCAmelCase (   snake_case__						):
			__UpperCamelCase				:      Optional[int]									=       requests.get(snake_case__						)
			__UpperCamelCase				:      Optional[Any]									=       np.array(Image.open(BytesIO(response.content						)						)						)
			return img

def       __lowerCAmelCase (   snake_case__						):
			__UpperCamelCase				:      Union[str, Any]									=       url.split("/"						)[-1]
			if fn not in os.listdir(os.getcwd()						):
						wget.download(snake_case__						)
			with open(snake_case__ ,				"rb"						) as stream:
						__UpperCamelCase				:      Tuple									=       pkl.load(snake_case__						)
			__UpperCamelCase				:      Optional[Any]									=       weights.pop("model"						)
			__UpperCamelCase				:      Tuple									=       {}
			for k, v in model.items():
						__UpperCamelCase				:      str									=       torch.from_numpy(snake_case__						)
						if "running_var" in k:
									__UpperCamelCase				:      List[str]									=       torch.tensor([0]						)
									__UpperCamelCase				:      str									=       k.replace("running_var" ,				"num_batches_tracked"						)
									__UpperCamelCase				:      Dict									=       zero
			return new

def       __lowerCAmelCase (   ):
			print(F"{os.path.abspath(os.path.join(snake_case__ ,				os.pardir						)						)}/demo.ipynb"						)

def       __lowerCAmelCase (   snake_case__ ,				snake_case__="RGB"						):
			assert isinstance(snake_case__ ,				snake_case__						)
			if os.path.isfile(snake_case__						):
						__UpperCamelCase				:      Optional[int]									=       cva.imread(snake_case__						)
			else:
						__UpperCamelCase				:      str									=       get_image_from_url(snake_case__						)
						assert img is not None, F"could not connect to: {im}"
			__UpperCamelCase				:      Any									=       cva.cvtColor(snake_case__ ,				cva.COLOR_BGR2RGB						)
			if input_format == "RGB":
						__UpperCamelCase				:      int									=       img[:, :, ::-1]
			return img




def       __lowerCAmelCase (   snake_case__ ,				snake_case__=1						):
			return (images[i : i + batch] for i in range(0 ,				len(snake_case__						) ,				snake_case__						))









'''simple docstring'''






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

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


_lowerCAmelCase				     = logging.get_logger(__name__)  # pylint: disable=invalid-name



class  A		(			SCREAMING_SNAKE_CASE__		):




				'''simple docstring'''





				A				     =    ["safety_checker", "feature_extractor"]
				def __init__(self			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase = True			,  )     ->	List[str]:
							super().__init__()
							if hasattr(scheduler.config			,  "steps_offset"      ) and scheduler.config.steps_offset != 1:
										__UpperCamelCase				:      List[str]									=       (
										    f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
										    f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
										    "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
										    " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
										    " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
										    " file"
										)
										deprecate("steps_offset!=1"			,  "1.0.0"			,  _UpperCAmelCase			,  standard_warn=_UpperCAmelCase      )
										__UpperCamelCase				:      str									=       dict(scheduler.config      )
										__UpperCamelCase				:      Optional[Any]									=       1
										__UpperCamelCase				:      Dict									=       FrozenDict(_UpperCAmelCase      )

							self.register_modules(
							    vae=_UpperCAmelCase			,  text_encoder=_UpperCAmelCase			,  tokenizer=_UpperCAmelCase			,  unet=_UpperCAmelCase			,  scheduler=_UpperCAmelCase			,  safety_checker=_UpperCAmelCase			,  feature_extractor=_UpperCAmelCase			,  )
							self.register_to_config(requires_safety_checker=_UpperCAmelCase      )
				@property
				def 	a_	(self      )     ->	Dict[str, Any]:
							return {k: getattr(self			,  _UpperCAmelCase      ) for k in self.config.keys() if not k.startswith("_"      )}
				def 	a_	(self			,  _UpperCAmelCase = "auto"      )     ->	List[str]:
							if slice_size == "auto":
										# half the attention head size is usually a good trade-off between
										# speed and memory
										__UpperCamelCase				:      Dict									=       self.unet.config.attention_head_dim // 2
							self.unet.set_attention_slice(_UpperCAmelCase      )
				def 	a_	(self      )     ->	Dict:
							self.enable_attention_slicing(_UpperCAmelCase      )
				@torch.no_grad()
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase = 0.8			,  _UpperCAmelCase = 5_0			,  _UpperCAmelCase = 7.5			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  _UpperCAmelCase = 0.0			,  _UpperCAmelCase = None			,  _UpperCAmelCase = "pil"			,  _UpperCAmelCase = True			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  )     ->	List[str]:
							# For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
							return StableDiffusionInpaintPipelineLegacy(**self.components      )(
							    prompt=_UpperCAmelCase			,  image=_UpperCAmelCase			,  mask_image=_UpperCAmelCase			,  strength=_UpperCAmelCase			,  num_inference_steps=_UpperCAmelCase			,  guidance_scale=_UpperCAmelCase			,  negative_prompt=_UpperCAmelCase			,  num_images_per_prompt=_UpperCAmelCase			,  eta=_UpperCAmelCase			,  generator=_UpperCAmelCase			,  output_type=_UpperCAmelCase			,  return_dict=_UpperCAmelCase			,  callback=_UpperCAmelCase			,  )
				@torch.no_grad()
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase = 0.8			,  _UpperCAmelCase = 5_0			,  _UpperCAmelCase = 7.5			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  _UpperCAmelCase = 0.0			,  _UpperCAmelCase = None			,  _UpperCAmelCase = "pil"			,  _UpperCAmelCase = True			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  **_UpperCAmelCase			,  )     ->	Optional[Any]:
							# For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
							return StableDiffusionImgaImgPipeline(**self.components      )(
							    prompt=_UpperCAmelCase			,  image=_UpperCAmelCase			,  strength=_UpperCAmelCase			,  num_inference_steps=_UpperCAmelCase			,  guidance_scale=_UpperCAmelCase			,  negative_prompt=_UpperCAmelCase			,  num_images_per_prompt=_UpperCAmelCase			,  eta=_UpperCAmelCase			,  generator=_UpperCAmelCase			,  output_type=_UpperCAmelCase			,  return_dict=_UpperCAmelCase			,  callback=_UpperCAmelCase			,  callback_steps=_UpperCAmelCase			,  )





				@torch.no_grad()
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase = 5_1_2			,  _UpperCAmelCase = 5_1_2			,  _UpperCAmelCase = 5_0			,  _UpperCAmelCase = 7.5			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  _UpperCAmelCase = 0.0			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  _UpperCAmelCase = "pil"			,  _UpperCAmelCase = True			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  )     ->	Union[str, Any]:
							# For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
							return StableDiffusionPipeline(**self.components      )(
							    prompt=_UpperCAmelCase			,  height=_UpperCAmelCase			,  width=_UpperCAmelCase			,  num_inference_steps=_UpperCAmelCase			,  guidance_scale=_UpperCAmelCase			,  negative_prompt=_UpperCAmelCase			,  num_images_per_prompt=_UpperCAmelCase			,  eta=_UpperCAmelCase			,  generator=_UpperCAmelCase			,  latents=_UpperCAmelCase			,  output_type=_UpperCAmelCase			,  return_dict=_UpperCAmelCase			,  callback=_UpperCAmelCase			,  callback_steps=_UpperCAmelCase			,  )



