





"""simple docstring"""





import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple

import numpy as np

from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
		from transformers.pipelines.conversational import Conversation


lowerCAmelCase__     			=			logging.get_logger(__name__)

lowerCAmelCase__     			=			{'''vocab_file''': '''vocab.txt''', '''emoji_file''': '''emoji.json'''}

lowerCAmelCase__     			=			{
    '''vocab_file''': {
        '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt''',
    },
    '''emoji_file''': {
        '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json''',
    },
}

lowerCAmelCase__     			=			{
    '''abeja/gpt-neox-japanese-2.7b''': 2_048,
}


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		with open(_SCREAMING_SNAKE_CASE  ,	"r"  ,	encoding="utf-8"    ) as f:
				UpperCamelCase   =	json.loads(f.read()    )

		UpperCamelCase   =	collections.OrderedDict()
		UpperCamelCase   =	collections.OrderedDict()
		UpperCamelCase   =	collections.OrderedDict()
		with open(_SCREAMING_SNAKE_CASE  ,	"r"  ,	encoding="utf-8"    ) as f:
				UpperCamelCase   =	f.readlines()
		UpperCamelCase   =	[[t.rstrip("\n"    )] if (t == "," or "," not in t) else t.rstrip("\n"    ).split(","    ) for t in token]
		for idx, b in enumerate(_SCREAMING_SNAKE_CASE    ):
				UpperCamelCase   =	b
				UpperCamelCase   =	idx
				for wd in b:
						UpperCamelCase   =	idx

		return vocab, raw_vocab, ids_to_tokens, emoji





class        _lowerCamelCase      (       _lowercase ):
						UpperCAmelCase_ =			VOCAB_FILES_NAMES
						UpperCAmelCase_ =			PRETRAINED_VOCAB_FILES_MAP
						UpperCAmelCase_ =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						UpperCAmelCase_ =			["input_ids", "attention_mask"]


						def __init__(self   ,							__a   ,							__a   ,							__a="<|endoftext|>"   ,							__a="<|endoftext|>"   ,							__a="<|startoftext|>"   ,							__a="<|endoftext|>"   ,							__a=False   ,							**__a   ,							) ->   List[Any]:
								super().__init__(
								    unk_token=__a   ,							pad_token=__a   ,							bos_token=__a   ,							eos_token=__a   ,							do_clean_text=__a   ,							**__a   ,							)
								if not os.path.isfile(__a		):
										raise ValueError(
										    F"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
										    " model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"		)
								if not os.path.isfile(__a		):
										raise ValueError(
										    F"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"
										    " pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"		)
								UpperCamelCase   =	do_clean_text
								UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   =	load_vocab_and_emoji(__a   ,							__a		)
								UpperCamelCase   =	SubWordJapaneseTokenizer(
								    vocab=self.vocab   ,							ids_to_tokens=self.ids_to_tokens   ,							emoji=self.emoji		)


						@property
						def     snake_case_   (self		) ->   List[str]:
								# self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
								return len(self.raw_vocab		)


						def     snake_case_   (self		) ->   List[Any]:
								return dict(self.raw_vocab   ,							**self.added_tokens_encoder		)


						def     snake_case_   (self   ,							__a		) ->   Any:
								return self.subword_tokenizer.tokenize(__a   ,							clean=self.do_clean_text		)


						def     snake_case_   (self   ,							__a		) ->   Any:
								return self.vocab.get(__a   ,							self.vocab.get(self.unk_token		)		)


						def     snake_case_   (self   ,							__a		) ->   Optional[Any]:
								return self.subword_tokenizer.convert_id_to_token(__a		)


						def     snake_case_   (self   ,							__a		) ->   Tuple:
								UpperCamelCase   =	"".join(__a		).strip()
								return out_string


						def     snake_case_   (self   ,							__a		) ->   List[int]:
								UpperCamelCase   =	[]
								for is_user, text in conversation.iter_texts():
										input_ids.extend(self.encode(__a   ,							add_special_tokens=__a		) + [self.eos_token_id]		)

								if len(__a		) > self.model_max_length:
										UpperCamelCase   =	input_ids[-self.model_max_length :]
								return input_ids




						def     snake_case_   (self   ,							__a   ,							__a = None		) ->   Tuple[str]:
								UpperCamelCase   =	0
								if os.path.isdir(__a		):
										UpperCamelCase   =	os.path.join(
										    __a   ,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)
										UpperCamelCase   =	os.path.join(
										    __a   ,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]		)
								else:
										UpperCamelCase   =	(
										    (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
										)
										UpperCamelCase   =	(
										    (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
										)
								with open(__a   ,							"w"   ,							encoding="utf-8"		) as writer:
										for token_index, token in self.ids_to_tokens.items():
												if index != token_index:
														logger.warning(
														    F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
														    " Please check that the vocabulary is not corrupted!"		)
														UpperCamelCase   =	token_index
												writer.write(",".join(__a		) + "\n"		)
												index += 1
								with open(__a   ,							"w"   ,							encoding="utf-8"		) as writer:
										json.dump(self.emoji   ,							__a		)
								return vocab_file, emoji_file





class        _lowerCamelCase      (       _lowercase ):


						def __init__(self   ,							__a   ,							__a   ,							__a		) ->   List[Any]:
								UpperCamelCase   =	vocab  # same as swe
								UpperCamelCase   =	ids_to_tokens  # same as bpe
								UpperCamelCase   =	emoji
								UpperCamelCase   =	np.max([len(__a		) for w in self.vocab.keys()]		)
								UpperCamelCase   =	re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)"		)
								UpperCamelCase   =	re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*"		)
								UpperCamelCase   =	re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}"		)
								UpperCamelCase   =	re.compile(
								    r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"		)
								UpperCamelCase   =	re.compile(
								    r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"		)
								UpperCamelCase   =	re.compile(
								    r"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*"		)
								UpperCamelCase   =	"─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
								UpperCamelCase   =	"▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
								UpperCamelCase   =	str.maketrans({k: "<BLOCK>" for k in keisen + blocks}		)


						def __len__(self		) ->   Tuple:
								return len(self.ids_to_tokens		)


						def     snake_case_   (self   ,							__a		) ->   Optional[Any]:
								UpperCamelCase   =	self.content_repattera.sub("<URL>"   ,							__a		)
								UpperCamelCase   =	self.content_repattera.sub("<EMAIL>"   ,							__a		)
								UpperCamelCase   =	self.content_repattera.sub("<TEL>"   ,							__a		)
								UpperCamelCase   =	self.content_repattera.sub("<DATE>"   ,							__a		)
								UpperCamelCase   =	self.content_repattera.sub("<DATE>"   ,							__a		)
								UpperCamelCase   =	self.content_repattera.sub("<PRICE>"   ,							__a		)
								UpperCamelCase   =	content.translate(self.content_transa		)
								while "<BLOCK><BLOCK>" in content:
										UpperCamelCase   =	content.replace("<BLOCK><BLOCK>"   ,							"<BLOCK>"		)
								return content


						def     snake_case_   (self   ,							__a   ,							__a=False		) ->   str:
								UpperCamelCase   =	text.replace(" "   ,							"<SP>"		)
								UpperCamelCase   =	text.replace("　"   ,							"<SP>"		)
								UpperCamelCase   =	text.replace("\r\n"   ,							"<BR>"		)
								UpperCamelCase   =	text.replace("\n"   ,							"<BR>"		)
								UpperCamelCase   =	text.replace("\r"   ,							"<BR>"		)
								UpperCamelCase   =	text.replace("\t"   ,							"<TAB>"		)
								UpperCamelCase   =	text.replace("—"   ,							"ー"		)
								UpperCamelCase   =	text.replace("−"   ,							"ー"		)
								for k, v in self.emoji["emoji"].items():
										if k in text:
												UpperCamelCase   =	text.replace(__a   ,							__a		)
								if clean:
										UpperCamelCase   =	self.clean_text(__a		)

								def check_simbol(__a		):
										UpperCamelCase   =	x.encode()
										if len(__a		) == 1 and len(__a		) == 2:
												UpperCamelCase   =	(int(e[0]		) << 8) + int(e[1]		)
												if (
												    (c >= 0Xc2a1 and c <= 0Xc2bf)
												    or (c >= 0Xc780 and c <= 0Xc783)
												    or (c >= 0Xcab9 and c <= 0Xcbbf)
												    or (c >= 0Xcc80 and c <= 0Xcda2)
												):
														return True
										return False

								def checkuae(__a		):
										UpperCamelCase   =	x.encode()
										if len(__a		) == 1 and len(__a		) == 3:
												UpperCamelCase   =	(int(e[0]		) << 16) + (int(e[1]		) << 8) + int(e[2]		)
												if c >= 0Xe28080 and c <= 0Xe2b07f:
														return True
										return False

								UpperCamelCase   =	0
								UpperCamelCase   =	[]
								while pos < len(__a		):
										UpperCamelCase   =	min(len(__a		)   ,							pos + self.maxlen + 1		) if text[pos] == "<" else pos + 3
										UpperCamelCase   =	[]  # (token_id, token, pos)
										for e in range(__a   ,							__a   ,							-1		):
												UpperCamelCase   =	text[pos:e]
												if wd in self.vocab:
														if wd[0] == "<" and len(__a		) > 2:
																UpperCamelCase   =	[(self.vocab[wd], wd, e)]
																break
														else:
																candidates.append((self.vocab[wd], wd, e)		)
										if len(__a		) > 0:
												# the smallest token_id is adopted
												UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   =	sorted(__a   ,							key=lambda __a		: x[0]		)[0]
												result.append(__a		)
												UpperCamelCase   =	e
										else:
												UpperCamelCase   =	pos + 1
												UpperCamelCase   =	text[pos:end]
												if check_simbol(__a		):
														result.append("<KIGOU>"		)
												elif checkuae(__a		):
														result.append("<U2000U2BFF>"		)
												else:
														for i in wd.encode("utf-8"		):
																result.append("<|byte%d|>" % i		)
												UpperCamelCase   =	end
								return result




						def     snake_case_   (self   ,							__a   ,							__a="\n"		) ->   int:
								UpperCamelCase   =	[]
								UpperCamelCase   =	[]
								UpperCamelCase   =	self.ids_to_tokens[index][0]
								if word[:6] == "<|byte" and word[-2:] == "|>":
										byte_tokens.append(int(word[6:-2]		)		)
								else:
										if len(__a		) > 0:
												words.append(bytearray(__a		).decode("utf-8"   ,							errors="replace"		)		)
												UpperCamelCase   =	[]
										if word[:7] == "<|emoji" and word[-2:] == "|>":
												words.append(self.emoji["emoji_inv"][word]		)
										elif word == "<SP>":
												words.append(" "		)
										elif word == "<BR>":
												words.append(__a		)
										elif word == "<TAB>":
												words.append("\t"		)
										elif word == "<BLOCK>":
												words.append("▀"		)
										elif word == "<KIGOU>":
												words.append("ǀ"		)
										elif word == "<U2000U2BFF>":
												words.append("‖"		)
										else:
												words.append(__a		)
								if len(__a		) > 0:
										words.append(bytearray(__a		).decode("utf-8"   ,							errors="replace"		)		)
								UpperCamelCase   =	"".join(__a		)
								return text













"""simple docstring"""





import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

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


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





class        _lowerCamelCase      (       _lowercase ):


						def __init__(self   ,							__a   ,							__a   ,							__a   ,							__a   ,							__a   ,							__a   ,							__a   ,							__a   ,							__a   ,							) ->   Dict:
								super().__init__()

								if safety_checker is None:
										logger.warning(
										    F"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
										    " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
										    " results in services or applications open to the public. Both the diffusers team and Hugging Face"
										    " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
										    " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
										    " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."		)

								self.register_modules(
								    speech_model=__a   ,							speech_processor=__a   ,							vae=__a   ,							text_encoder=__a   ,							tokenizer=__a   ,							unet=__a   ,							scheduler=__a   ,							feature_extractor=__a   ,							)


						def     snake_case_   (self   ,							__a = "auto"		) ->   str:
								if slice_size == "auto":
										UpperCamelCase   =	self.unet.config.attention_head_dim // 2
								self.unet.set_attention_slice(__a		)


						def     snake_case_   (self		) ->   List[Any]:
								self.enable_attention_slicing(__a		)




						@torch.no_grad()
						def __call__(self   ,							__a   ,							__a=1_60_00   ,							__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   ,							) ->   List[str]:
								UpperCamelCase   =	self.speech_processor.feature_extractor(
								    __a   ,							return_tensors="pt"   ,							sampling_rate=__a		).input_features.to(self.device		)
								UpperCamelCase   =	self.speech_model.generate(__a   ,							max_length=48_00_00		)

								UpperCamelCase   =	self.speech_processor.tokenizer.batch_decode(__a   ,							skip_special_tokens=__a   ,							normalize=__a		)[
								    0
								]

								if isinstance(__a   ,							__a		):
										UpperCamelCase   =	1
								elif isinstance(__a   ,							__a		):
										UpperCamelCase   =	len(__a		)
								else:
										raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__a		)}"		)

								if height % 8 != 0 or width % 8 != 0:
										raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}."		)

								if (callback_steps is None) or (
								    callback_steps is not None and (not isinstance(__a   ,							__a		) or callback_steps <= 0)
								):
										raise ValueError(
										    F"`callback_steps` has to be a positive integer but is {callback_steps} of type"
										    F" {type(__a		)}."		)

								# get prompt text embeddings
								UpperCamelCase   =	self.tokenizer(
								    __a   ,							padding="max_length"   ,							max_length=self.tokenizer.model_max_length   ,							return_tensors="pt"   ,							)
								UpperCamelCase   =	text_inputs.input_ids

								if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
										UpperCamelCase   =	self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]		)
										logger.warning(
										    "The following part of your input was truncated because CLIP can only handle sequences up to"
										    F" {self.tokenizer.model_max_length} tokens: {removed_text}"		)
										UpperCamelCase   =	text_input_ids[:, : self.tokenizer.model_max_length]
								UpperCamelCase   =	self.text_encoder(text_input_ids.to(self.device		)		)[0]

								# duplicate text embeddings for each generation per prompt, using mps friendly method
								UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   =	text_embeddings.shape
								UpperCamelCase   =	text_embeddings.repeat(1   ,							__a   ,							1		)
								UpperCamelCase   =	text_embeddings.view(bs_embed * num_images_per_prompt   ,							__a   ,							-1		)

								# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
								# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
								# corresponds to doing no classifier free guidance.
								UpperCamelCase   =	guidance_scale > 1.0
								# get unconditional embeddings for classifier free guidance
								if do_classifier_free_guidance:
										UpperCamelCase   =	42
										if negative_prompt is None:
												UpperCamelCase   =	[""] * batch_size
										elif type(__a		) is not type(__a		):
												raise TypeError(
												    F"`negative_prompt` should be the same type to `prompt`, but got {type(__a		)} !="
												    F" {type(__a		)}."		)
										elif isinstance(__a   ,							__a		):
												UpperCamelCase   =	[negative_prompt]
										elif batch_size != len(__a		):
												raise ValueError(
												    F"`negative_prompt`: {negative_prompt} has batch size {len(__a		)}, but `prompt`:"
												    F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
												    " the batch size of `prompt`."		)
										else:
												UpperCamelCase   =	negative_prompt

										UpperCamelCase   =	text_input_ids.shape[-1]
										UpperCamelCase   =	self.tokenizer(
										    __a   ,							padding="max_length"   ,							max_length=__a   ,							truncation=__a   ,							return_tensors="pt"   ,							)
										UpperCamelCase   =	self.text_encoder(uncond_input.input_ids.to(self.device		)		)[0]

										# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
										UpperCamelCase   =	uncond_embeddings.shape[1]
										UpperCamelCase   =	uncond_embeddings.repeat(1   ,							__a   ,							1		)
										UpperCamelCase   =	uncond_embeddings.view(batch_size * num_images_per_prompt   ,							__a   ,							-1		)

										# For classifier free guidance, we need to do two forward passes.
										# Here we concatenate the unconditional and text embeddings into a single batch
										# to avoid doing two forward passes
										UpperCamelCase   =	torch.cat([uncond_embeddings, text_embeddings]		)

								# get the initial random noise unless the user supplied it

								# Unlike in other pipelines, latents need to be generated in the target device
								# for 1-to-1 results reproducibility with the CompVis implementation.
								# However this currently doesn't work in `mps`.
								UpperCamelCase   =	(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
								UpperCamelCase   =	text_embeddings.dtype
								if latents is None:
										if self.device.type == "mps":
												# randn does not exist on mps
												UpperCamelCase   =	torch.randn(__a   ,							generator=__a   ,							device="cpu"   ,							dtype=__a		).to(
												    self.device		)
										else:
												UpperCamelCase   =	torch.randn(__a   ,							generator=__a   ,							device=self.device   ,							dtype=__a		)
								else:
										if latents.shape != latents_shape:
												raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"		)
										UpperCamelCase   =	latents.to(self.device		)

								# set timesteps
								self.scheduler.set_timesteps(__a		)

								# Some schedulers like PNDM have timesteps as arrays
								# It's more optimized to move all timesteps to correct device beforehand
								UpperCamelCase   =	self.scheduler.timesteps.to(self.device		)

								# scale the initial noise by the standard deviation required by the scheduler
								UpperCamelCase   =	latents * self.scheduler.init_noise_sigma

								# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
								# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
								# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
								# and should be between [0, 1]
								UpperCamelCase   =	"eta" in set(inspect.signature(self.scheduler.step		).parameters.keys()		)
								UpperCamelCase   =	{}
								if accepts_eta:
										UpperCamelCase   =	eta

								for i, t in enumerate(self.progress_bar(__a		)		):
										# expand the latents if we are doing classifier free guidance
										UpperCamelCase   =	torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
										UpperCamelCase   =	self.scheduler.scale_model_input(__a   ,							__a		)

										# predict the noise residual
										UpperCamelCase   =	self.unet(__a   ,							__a   ,							encoder_hidden_states=__a		).sample

										# perform guidance
										if do_classifier_free_guidance:
												UpperCamelCase   ,				UpperCamelCase   =	noise_pred.chunk(2		)
												UpperCamelCase   =	noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

										# compute the previous noisy sample x_t -> x_t-1
										UpperCamelCase   =	self.scheduler.step(__a   ,							__a   ,							__a   ,							**__a		).prev_sample

										# call the callback, if provided
										if callback is not None and i % callback_steps == 0:
												callback(__a   ,							__a   ,							__a		)

								UpperCamelCase   =	1 / 0.18215 * latents
								UpperCamelCase   =	self.vae.decode(__a		).sample

								UpperCamelCase   =	(image / 2 + 0.5).clamp(0   ,							1		)

								# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
								UpperCamelCase   =	image.cpu().permute(0   ,							2   ,							3   ,							1		).float().numpy()

								if output_type == "pil":
										UpperCamelCase   =	self.numpy_to_pil(__a		)

								if not return_dict:
										return image

								return StableDiffusionPipelineOutput(images=__a   ,							nsfw_content_detected=__a		)






