





"""simple docstring"""


import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


__magic_name__       :					str						=			datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
		import pyspark






@dataclass
class 							lowercase__			(   datasets.BuilderConfig	):

			"""simple docstring"""
			__lowerCAmelCase     :				Optional[datasets.Features]										=  None


def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     ):
						import pyspark

						def generate_fn():
												UpperCamelCase				:		List[str]				   =			df.select("""*"""							,     pyspark.sql.functions.spark_partition_id().alias("""part_id"""     )     )
												for partition_id in partition_order:
																		UpperCamelCase				:		List[str]				   =			df_with_partition_id.select("""*"""     ).where(f"""part_id = {partition_id}"""     ).drop("""part_id"""     )
																		UpperCamelCase				:		Optional[Any]				   =			partition_df.collect()
																		UpperCamelCase				:		Union[str, Any]				   =			0
																		for row in rows:
																								yield f"""{partition_id}_{row_id}""", row.asDict()
																								row_id += 1

						return generate_fn






class 							lowercase__			(   _BaseExamplesIterable	):

			"""simple docstring"""







			def __init__(      self						,   _A						,   _A=None						,   ):






									'''simple docstring'''







									UpperCamelCase				:		Optional[Any]				   =			df
									UpperCamelCase				:		Tuple				   =			partition_order or range(self.df.rdd.getNumPartitions()    )
									UpperCamelCase				:		Union[str, Any]				   =			_generate_iterable_examples(self.df						,   self.partition_order    )







			def __iter__(      self    ):






									'''simple docstring'''







									yield from self.generate_examples_fn()







			def   _a      (      self						,   _A    ):






									'''simple docstring'''







									UpperCamelCase				:		int				   =			list(range(self.df.rdd.getNumPartitions()    )    )
									generator.shuffle(_A    )
									return SparkExamplesIterable(self.df						,   partition_order=_A    )







			def   _a      (      self						,   _A						,   _A    ):






									'''simple docstring'''







									UpperCamelCase				:		Optional[int]				   =			self.split_shard_indices_by_worker(_A						,   _A    )
									return SparkExamplesIterable(self.df						,   partition_order=_A    )







			@property
			def   _a      (      self    ):






									'''simple docstring'''







									return len(self.partition_order    )






class 							lowercase__			(   datasets.DatasetBuilder	):

			"""simple docstring"""
			__lowerCAmelCase     :				Dict										=  SparkConfig







			def __init__(      self						,   _A						,   _A = None						,   _A = None						,   **_A						,   ):






									'''simple docstring'''







									import pyspark

									UpperCamelCase				:		Optional[int]				   =			pyspark.sql.SparkSession.builder.getOrCreate()
									UpperCamelCase				:		List[str]				   =			df
									UpperCamelCase				:		Optional[Any]				   =			working_dir

									super().__init__(
									    cache_dir=_A						,   config_name=str(self.df.semanticHash()    )						,   **_A						,   )







			def   _a      (      self    ):






									'''simple docstring'''







									def create_cache_and_write_probe(_A    ):
															# makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
															# already exist.
															os.makedirs(self._cache_dir						,   exist_ok=_A    )
															UpperCamelCase				:		List[Any]				   =			os.path.join(self._cache_dir						,   """fs_test""" + uuid.uuida().hex    )
															# Opening the file in append mode will create a new file unless it already exists, in which case it will not
															# change the file contents.
															open(_A						,   """a"""    )
															return [probe_file]

									if self._spark.conf.get("""spark.master"""						,   """"""    ).startswith("""local"""    ):
															return

									# If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
									# accessible to the driver.
									# TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
									if self._cache_dir:
															UpperCamelCase				:		Tuple				   =			(
															    self._spark.sparkContext.parallelize(range(1    )						,   1    ).mapPartitions(_A    ).collect()
															)
															if os.path.isfile(probe[0]    ):
																					return

									raise ValueError(
									    """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir"""    )







			def   _a      (      self    ):






									'''simple docstring'''







									return datasets.DatasetInfo(features=self.config.features    )







			def   _a      (      self						,   _A    ):






									'''simple docstring'''







									return [datasets.SplitGenerator(name=datasets.Split.TRAIN    )]







			def   _a      (      self						,   _A    ):






									'''simple docstring'''







									import pyspark

									def get_arrow_batch_size(_A    ):
															for batch in it:
																					yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]}    )

									UpperCamelCase				:		Tuple				   =			self.df.count()
									UpperCamelCase				:		Union[str, Any]				   =			df_num_rows if df_num_rows <= 1_0_0 else 1_0_0
									# Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
									UpperCamelCase				:		List[Any]				   =			(
									    self.df.limit(_A    )
									    .repartition(1    )
									    .mapInArrow(_A						,   """batch_bytes: long"""    )
									    .agg(pyspark.sql.functions.sum("""batch_bytes"""    ).alias("""sample_bytes"""    )    )
									    .collect()[0]
									    .sample_bytes
									    / sample_num_rows
									)
									UpperCamelCase				:		str				   =			approx_bytes_per_row * df_num_rows
									if approx_total_size > max_shard_size:
															# Make sure there is at least one row per partition.
															UpperCamelCase				:		int				   =			min(_A						,   int(approx_total_size / max_shard_size    )    )
															UpperCamelCase				:		Optional[Any]				   =			self.df.repartition(_A    )







			def   _a      (      self						,   _A						,   _A						,   _A						,   ):






									'''simple docstring'''







									import pyspark

									UpperCamelCase				:		List[Any]				   =			ParquetWriter if file_format == """parquet""" else ArrowWriter
									UpperCamelCase				:		Dict				   =			os.path.join(self._working_dir						,   os.path.basename(_A    )    ) if self._working_dir else fpath
									UpperCamelCase				:		List[Any]				   =			file_format == """parquet"""

									# Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
									# pickling the SparkContext.
									UpperCamelCase				:		Optional[int]				   =			self.config.features
									UpperCamelCase				:		Optional[Any]				   =			self._writer_batch_size
									UpperCamelCase				:		Union[str, Any]				   =			self._fs.storage_options

									def write_arrow(_A    ):
															# Within the same SparkContext, no two task attempts will share the same attempt ID.
															UpperCamelCase				:		Optional[int]				   =			pyspark.TaskContext().taskAttemptId()
															UpperCamelCase				:		str				   =			next(_A						,   _A    )
															if first_batch is None:
																					# Some partitions might not receive any data.
																					return pa.RecordBatch.from_arrays(
																					    [[task_id], [0], [0]]						,   names=["""task_id""", """num_examples""", """num_bytes"""]						,   )
															UpperCamelCase				:		str				   =			0
															UpperCamelCase				:		Union[str, Any]				   =			writer_class(
															    features=_A						,   path=working_fpath.replace("""SSSSS"""						,   f"""{shard_id:05d}"""    ).replace("""TTTTT"""						,   f"""{task_id:05d}"""    )						,   writer_batch_size=_A						,   storage_options=_A						,   embed_local_files=_A						,   )
															UpperCamelCase				:		List[str]				   =			pa.Table.from_batches([first_batch]    )
															writer.write_table(_A    )
															for batch in it:
																					if max_shard_size is not None and writer._num_bytes >= max_shard_size:
																											UpperCamelCase   ,						UpperCamelCase				:		Any				   =			writer.finalize()
																											writer.close()
																											yield pa.RecordBatch.from_arrays(
																											    [[task_id], [num_examples], [num_bytes]]						,   names=["""task_id""", """num_examples""", """num_bytes"""]						,   )
																											shard_id += 1
																											UpperCamelCase				:		Any				   =			writer_class(
																											    features=writer._features						,   path=working_fpath.replace("""SSSSS"""						,   f"""{shard_id:05d}"""    ).replace("""TTTTT"""						,   f"""{task_id:05d}"""    )						,   writer_batch_size=_A						,   storage_options=_A						,   embed_local_files=_A						,   )
																					UpperCamelCase				:		Dict				   =			pa.Table.from_batches([batch]    )
																					writer.write_table(_A    )

															if writer._num_bytes > 0:
																					UpperCamelCase   ,						UpperCamelCase				:		Any				   =			writer.finalize()
																					writer.close()
																					yield pa.RecordBatch.from_arrays(
																					    [[task_id], [num_examples], [num_bytes]]						,   names=["""task_id""", """num_examples""", """num_bytes"""]						,   )

															if working_fpath != fpath:
																					for file in os.listdir(os.path.dirname(_A    )    ):
																											UpperCamelCase				:		Optional[int]				   =			os.path.join(os.path.dirname(_A    )						,   os.path.basename(_A    )    )
																											shutil.move(_A						,   _A    )

									UpperCamelCase				:		int				   =			(
									    self.df.mapInArrow(_A						,   """task_id: long, num_examples: long, num_bytes: long"""    )
									    .groupBy("""task_id"""    )
									    .agg(
									        pyspark.sql.functions.sum("""num_examples"""    ).alias("""total_num_examples"""    )						,   pyspark.sql.functions.sum("""num_bytes"""    ).alias("""total_num_bytes"""    )						,   pyspark.sql.functions.count("""num_bytes"""    ).alias("""num_shards"""    )						,   pyspark.sql.functions.collect_list("""num_examples"""    ).alias("""shard_lengths"""    )						,   )
									    .collect()
									)
									for row in stats:
															yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)







			def   _a      (      self						,   _A						,   _A = "arrow"						,   _A = None						,   _A = None						,   **_A						,   ):






									'''simple docstring'''







									self._validate_cache_dir()

									UpperCamelCase				:		Dict				   =			convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE    )
									self._repartition_df_if_needed(_A    )
									UpperCamelCase				:		Optional[int]				   =			not is_remote_filesystem(self._fs    )
									UpperCamelCase				:		Dict				   =			os.path.join if is_local else posixpath.join

									UpperCamelCase				:		Optional[int]				   =			"""-TTTTT-SSSSS-of-NNNNN"""
									UpperCamelCase				:		Dict				   =			f"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}"""
									UpperCamelCase				:		Any				   =			path_join(self._output_dir						,   _A    )

									UpperCamelCase				:		Any				   =			0
									UpperCamelCase				:		List[str]				   =			0
									UpperCamelCase				:		str				   =			0
									UpperCamelCase				:		Union[str, Any]				   =			[]
									UpperCamelCase				:		str				   =			[]

									for task_id, content in self._prepare_split_single(_A						,   _A						,   _A    ):
															(
															    (
															    UpperCamelCase
															)   ,						(
															    UpperCamelCase
															)   ,						(
															    UpperCamelCase
															)   ,						(
															    UpperCamelCase
															)   ,						
															)				:		Dict				   =			content
															if num_bytes > 0:
																					total_num_examples += num_examples
																					total_num_bytes += num_bytes
																					total_shards += num_shards
																					task_id_and_num_shards.append((task_id, num_shards)    )
																					all_shard_lengths.extend(_A    )

									UpperCamelCase				:		str				   =			total_num_examples
									UpperCamelCase				:		Tuple				   =			total_num_bytes

									# should rename everything at the end
									logger.debug(f"""Renaming {total_shards} shards."""    )
									if total_shards > 1:
															UpperCamelCase				:		List[Any]				   =			all_shard_lengths

															# Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
															# pickling error due to pickling the SparkContext.
															UpperCamelCase				:		List[Any]				   =			self._fs

															# use the -SSSSS-of-NNNNN pattern
															def _rename_shard(
															    _A						,   _A						,   _A						,   ):
																					rename(
																					    _A						,   fpath.replace("""SSSSS"""						,   f"""{shard_id:05d}"""    ).replace("""TTTTT"""						,   f"""{task_id:05d}"""    )						,   fpath.replace("""TTTTT-SSSSS"""						,   f"""{global_shard_id:05d}"""    ).replace("""NNNNN"""						,   f"""{total_shards:05d}"""    )						,   )

															UpperCamelCase				:		str				   =			[]
															UpperCamelCase				:		List[Any]				   =			0
															for i in range(len(_A    )    ):
																					UpperCamelCase   ,						UpperCamelCase				:		Dict				   =			task_id_and_num_shards[i]
																					for shard_id in range(_A    ):
																											args.append([task_id, shard_id, global_shard_id]    )
																											global_shard_id += 1
															self._spark.sparkContext.parallelize(_A						,   len(_A    )    ).map(lambda _A    : _rename_shard(*_A    )    ).collect()
									else:
															# don't use any pattern
															UpperCamelCase				:		int				   =			0
															UpperCamelCase				:		Any				   =			task_id_and_num_shards[0][0]
															self._rename(
															    fpath.replace("""SSSSS"""						,   f"""{shard_id:05d}"""    ).replace("""TTTTT"""						,   f"""{task_id:05d}"""    )						,   fpath.replace(_A						,   """"""    )						,   )







			def   _a      (      self						,   _A						,   ):






									'''simple docstring'''







									return SparkExamplesIterable(self.df    )










"""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


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






class 							lowercase__			(   __SCREAMING_SNAKE_CASE	):

			"""simple docstring"""







			def __init__(      self						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   ):






									'''simple docstring'''







									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   _a      (      self						,   _A = "auto"    ):






									'''simple docstring'''







									if slice_size == "auto":
															UpperCamelCase				:		List[Any]				   =			self.unet.config.attention_head_dim // 2
									self.unet.set_attention_slice(_A    )







			def   _a      (      self    ):






									'''simple docstring'''







									self.enable_attention_slicing(_A    )







			@torch.no_grad()
			def __call__(      self						,   _A						,   _A=1_6_0_0_0						,   _A = 5_1_2						,   _A = 5_1_2						,   _A = 5_0						,   _A = 7.5						,   _A = None						,   _A = 1						,   _A = 0.0						,   _A = None						,   _A = None						,   _A = "pil"						,   _A = True						,   _A = None						,   _A = 1						,   **_A						,   ):






									'''simple docstring'''







									UpperCamelCase				:		str				   =			self.speech_processor.feature_extractor(
									    _A						,   return_tensors="""pt"""						,   sampling_rate=_A    ).input_features.to(self.device    )
									UpperCamelCase				:		List[Any]				   =			self.speech_model.generate(_A						,   max_length=4_8_0_0_0_0    )

									UpperCamelCase				:		Optional[int]				   =			self.speech_processor.tokenizer.batch_decode(_A						,   skip_special_tokens=_A						,   normalize=_A    )[
									    0
									]

									if isinstance(_A						,   _A    ):
															UpperCamelCase				:		Tuple				   =			1
									elif isinstance(_A						,   _A    ):
															UpperCamelCase				:		List[Any]				   =			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				:		Dict				   =			self.tokenizer(
									    _A						,   padding="""max_length"""						,   max_length=self.tokenizer.model_max_length						,   return_tensors="""pt"""						,   )
									UpperCamelCase				:		Dict				   =			text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
															UpperCamelCase				:		Tuple				   =			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				:		int				   =			text_input_ids[:, : self.tokenizer.model_max_length]
									UpperCamelCase				:		List[str]				   =			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				:		Optional[Any]				   =			text_embeddings.shape
									UpperCamelCase				:		Optional[int]				   =			text_embeddings.repeat(1						,   _A						,   1    )
									UpperCamelCase				:		Union[str, Any]				   =			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				:		Optional[Any]				   =			guidance_scale > 1.0
									# get unconditional embeddings for classifier free guidance
									if do_classifier_free_guidance:
															UpperCamelCase				:		List[str]
															if negative_prompt is None:
																					UpperCamelCase				:		str				   =			[""""""] * 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				:		Tuple				   =			[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				:		Any				   =			negative_prompt

															UpperCamelCase				:		Optional[int]				   =			text_input_ids.shape[-1]
															UpperCamelCase				:		List[str]				   =			self.tokenizer(
															    _A						,   padding="""max_length"""						,   max_length=_A						,   truncation=_A						,   return_tensors="""pt"""						,   )
															UpperCamelCase				:		Optional[int]				   =			self.text_encoder(uncond_input.input_ids.to(self.device    )    )[0]

															# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
															UpperCamelCase				:		List[Any]				   =			uncond_embeddings.shape[1]
															UpperCamelCase				:		Dict				   =			uncond_embeddings.repeat(1						,   _A						,   1    )
															UpperCamelCase				:		Dict				   =			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				:		str				   =			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				:		Any				   =			(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
									UpperCamelCase				:		int				   =			text_embeddings.dtype
									if latents is None:
															if self.device.type == "mps":
																					# randn does not exist on mps
																					UpperCamelCase				:		Tuple				   =			torch.randn(_A						,   generator=_A						,   device="""cpu"""						,   dtype=_A    ).to(
																					    self.device    )
															else:
																					UpperCamelCase				:		Any				   =			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				:		Optional[Any]				   =			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				:		Tuple				   =			self.scheduler.timesteps.to(self.device    )

									# scale the initial noise by the standard deviation required by the scheduler
									UpperCamelCase				:		Any				   =			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				:		List[Any]				   =			"""eta""" in set(inspect.signature(self.scheduler.step    ).parameters.keys()    )
									UpperCamelCase				:		str				   =			{}
									if accepts_eta:
															UpperCamelCase				:		Union[str, Any]				   =			eta

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

															# predict the noise residual
															UpperCamelCase				:		Optional[Any]				   =			self.unet(_A						,   _A						,   encoder_hidden_states=_A    ).sample

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

															# compute the previous noisy sample x_t -> x_t-1
															UpperCamelCase				:		Any				   =			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				:		Optional[Any]				   =			1 / 0.1_82_15 * latents
									UpperCamelCase				:		Union[str, Any]				   =			self.vae.decode(_A    ).sample

									UpperCamelCase				:		List[Any]				   =			(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				:		Dict				   =			image.cpu().permute(0						,   2						,   3						,   1    ).float().numpy()

									if output_type == "pil":
															UpperCamelCase				:		Optional[Any]				   =			self.numpy_to_pil(_A    )

									if not return_dict:
															return image

									return StableDiffusionPipelineOutput(images=_A						,   nsfw_content_detected=_A    )



