


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

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import DiffusionPipeline
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import logging


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



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Tuple							,			snake_case					:		Optional[int]							,			snake_case					:		Dict							,			snake_case					:		Tuple							,			snake_case					:		Any							,			snake_case					:		List[str]							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[int]							,			)						->							Dict:
          super().__init__()
          self.register_modules(
              vae=__lowerCAmelCase							,			text_encoder=__lowerCAmelCase							,			tokenizer=__lowerCAmelCase							,			unet=__lowerCAmelCase							,			scheduler=__lowerCAmelCase							,			safety_checker=__lowerCAmelCase							,			feature_extractor=__lowerCAmelCase							,			)

     def 			lowerCamelCase__			(    self					:		Optional[int]							,			snake_case					:		Union[str, Any] = "auto"      )						->							str:



          if slice_size == "auto":
               # half the attention head size is usually a good trade-off between
               # speed and memory
               __UpperCAmelCase     :			Union[str, Any]  							=      self.unet.config.attention_head_dim // 2
          self.unet.set_attention_slice(__lowerCAmelCase      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Dict:
          self.enable_attention_slicing(__lowerCAmelCase      )






     @torch.no_grad()
     def __call__(    self					:		Tuple							,			snake_case					:		int							,			snake_case					:		Optional[int] = 512							,			snake_case					:		Dict = 512							,			snake_case					:		Optional[Any] = 50							,			snake_case					:		List[str] = 7.5							,			snake_case					:		Dict = None							,			snake_case					:		Dict = 1							,			snake_case					:		str = 0.0							,			snake_case					:		str = None							,			snake_case					:		int = None							,			snake_case					:		str = "pil"							,			snake_case					:		str = True							,			snake_case					:		Optional[Any] = None							,			snake_case					:		Optional[Any] = 1							,			snake_case					:		Optional[int] = None							,			**snake_case					:		Any							,			)						->							Union[str, Any]:



          if isinstance(__lowerCAmelCase							,			__lowerCAmelCase      ):
               __UpperCAmelCase     :			Any  							=      1
          elif isinstance(__lowerCAmelCase							,			__lowerCAmelCase      ):
               __UpperCAmelCase     :			Optional[Any]  							=      len(__lowerCAmelCase      )
          else:
               raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(__lowerCAmelCase      )}'      )

          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(__lowerCAmelCase							,			__lowerCAmelCase      ) or callback_steps <= 0)
          ):
               raise ValueError(
                   f'`callback_steps` has to be a positive integer but is {callback_steps} of type'
                   f' {type(__lowerCAmelCase      )}.'      )

          # get prompt text embeddings
          __UpperCAmelCase     :			List[str]  							=      self.tokenizer(
              __lowerCAmelCase							,			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     :			Any  							=      text_input_ids[:, : self.tokenizer.model_max_length]

          if text_embeddings is None:
               __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     :			int  							=      text_embeddings.shape
          __UpperCAmelCase     :			str  							=      text_embeddings.repeat(1							,			__lowerCAmelCase							,			1      )
          __UpperCAmelCase     :			str  							=      text_embeddings.view(bs_embed * num_images_per_prompt							,			__lowerCAmelCase							,			-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     :			List[str]  							=      guidance_scale > 1.0
          # get unconditional embeddings for classifier free guidance
          if do_classifier_free_guidance:
               __UpperCAmelCase     :			Optional[int]  							=      42
               if negative_prompt is None:
                    __UpperCAmelCase     :			List[str]  							=      ['''''']
               elif type(__lowerCAmelCase      ) is not type(__lowerCAmelCase      ):
                    raise TypeError(
                        f'`negative_prompt` should be the same type to `prompt`, but got {type(__lowerCAmelCase      )} !='
                        f' {type(__lowerCAmelCase      )}.'      )
               elif isinstance(__lowerCAmelCase							,			__lowerCAmelCase      ):
                    __UpperCAmelCase     :			Dict  							=      [negative_prompt]
               elif batch_size != len(__lowerCAmelCase      ):
                    raise ValueError(
                        f'`negative_prompt`: {negative_prompt} has batch size {len(__lowerCAmelCase      )}, but `prompt`:'
                        f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'
                        ''' the batch size of `prompt`.'''      )
               else:
                    __UpperCAmelCase     :			str  							=      negative_prompt

               __UpperCAmelCase     :			List[str]  							=      text_input_ids.shape[-1]
               __UpperCAmelCase     :			Dict  							=      self.tokenizer(
                   __lowerCAmelCase							,			padding='''max_length'''							,			max_length=__lowerCAmelCase							,			truncation=__lowerCAmelCase							,			return_tensors='''pt'''							,			)
               __UpperCAmelCase     :			List[Any]  							=      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[str]  							=      uncond_embeddings.shape[1]
               __UpperCAmelCase     :			List[str]  							=      uncond_embeddings.repeat(__lowerCAmelCase							,			__lowerCAmelCase							,			1      )
               __UpperCAmelCase     :			Any  							=      uncond_embeddings.view(batch_size * num_images_per_prompt							,			__lowerCAmelCase							,			-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     :			Optional[int]  							=      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     :			str  							=      (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64)
          __UpperCAmelCase     :			List[str]  							=      text_embeddings.dtype
          if latents is None:
               if self.device.type == "mps":
                    # randn does not exist on mps
                    __UpperCAmelCase     :			Any  							=      torch.randn(
                        __lowerCAmelCase							,			generator=__lowerCAmelCase							,			device='''cpu'''							,			dtype=__lowerCAmelCase      ).to(self.device      )
                    __UpperCAmelCase     :			Tuple  							=      torch.randn(__lowerCAmelCase							,			generator=__lowerCAmelCase							,			device='''cpu'''							,			dtype=__lowerCAmelCase      ).to(
                        self.device      )
               else:
                    __UpperCAmelCase     :			List[str]  							=      torch.randn(
                        __lowerCAmelCase							,			generator=__lowerCAmelCase							,			device=self.device							,			dtype=__lowerCAmelCase      )
                    __UpperCAmelCase     :			Dict  							=      torch.randn(__lowerCAmelCase							,			generator=__lowerCAmelCase							,			device=self.device							,			dtype=__lowerCAmelCase      )
          else:
               if latents_reference.shape != latents_shape:
                    raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}'      )
               __UpperCAmelCase     :			int  							=      latents_reference.to(self.device      )
               __UpperCAmelCase     :			List[Any]  							=      latents.to(self.device      )

          # This is the key part of the pipeline where we
          # try to ensure that the generated images w/ the same seed
          # but different sizes actually result in similar images
          __UpperCAmelCase     :			Dict  							=      (latents_shape[3] - latents_shape_reference[3]) // 2
          __UpperCAmelCase     :			Optional[int]  							=      (latents_shape[2] - latents_shape_reference[2]) // 2
          __UpperCAmelCase     :			Any  							=      latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
          __UpperCAmelCase     :			str  							=      latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
          __UpperCAmelCase     :			Union[str, Any]  							=      0 if dx < 0 else dx
          __UpperCAmelCase     :			Any  							=      0 if dy < 0 else dy
          __UpperCAmelCase     :			Dict  							=      max(-dx							,			0      )
          __UpperCAmelCase     :			Any  							=      max(-dy							,			0      )
          # import pdb
          # pdb.set_trace()
          __UpperCAmelCase     :			List[Any]  							=      latents_reference[:, :, dy : dy + h, dx : dx + w]

          # set timesteps
          self.scheduler.set_timesteps(__lowerCAmelCase      )

          # Some schedulers like PNDM have timesteps as arrays
          # It's more optimized to move all timesteps to correct device beforehand
          __UpperCAmelCase     :			Union[str, Any]  							=      self.scheduler.timesteps.to(self.device      )

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

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

               # predict the noise residual
               __UpperCAmelCase     :			Union[str, Any]  							=      self.unet(__lowerCAmelCase							,			__lowerCAmelCase							,			encoder_hidden_states=__lowerCAmelCase      ).sample

               # perform guidance
               if do_classifier_free_guidance:
                    __UpperCAmelCase							,       __UpperCAmelCase     :			Optional[Any]  							=      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     :			Optional[int]  							=      self.scheduler.step(__lowerCAmelCase							,			__lowerCAmelCase							,			__lowerCAmelCase							,			**__lowerCAmelCase      ).prev_sample

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

          __UpperCAmelCase     :			List[Any]  							=      1 / 0.18_215 * latents
          __UpperCAmelCase     :			Any  							=      self.vae.decode(__lowerCAmelCase      ).sample

          __UpperCAmelCase     :			Optional[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     :			Tuple  							=      image.cpu().permute(0							,			2							,			3							,			1      ).float().numpy()

          if self.safety_checker is not None:
               __UpperCAmelCase     :			List[str]  							=      self.feature_extractor(self.numpy_to_pil(__lowerCAmelCase      )							,			return_tensors='''pt'''      ).to(
                   self.device      )
               __UpperCAmelCase							,       __UpperCAmelCase     :			Optional[Any]  							=      self.safety_checker(
                   images=__lowerCAmelCase							,			clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype      )      )
          else:
               __UpperCAmelCase     :			Optional[int]  							=      None

          if output_type == "pil":
               __UpperCAmelCase     :			Any  							=      self.numpy_to_pil(__lowerCAmelCase      )

          if not return_dict:
               return (image, has_nsfw_concept)

          return StableDiffusionPipelineOutput(images=__lowerCAmelCase							,			nsfw_content_detected=__lowerCAmelCase      )



'''simple docstring'''



import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


__UpperCAmelCase      :int			    =       datasets.utils.logging.get_logger(__name__)



@dataclass
class      a    (		datasets.BuilderConfig	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Optional[datasets.Features]							       =       None
     SCREAMING_SNAKE_CASE	:			str							       =       "utf-8"
     SCREAMING_SNAKE_CASE	:			Optional[str]							       =       None
     SCREAMING_SNAKE_CASE	:			Optional[str]							       =       None
     SCREAMING_SNAKE_CASE	:			bool							       =       True  # deprecated
     SCREAMING_SNAKE_CASE	:			Optional[int]							       =       None  # deprecated
     SCREAMING_SNAKE_CASE	:			int							       =       1_0 << 2_0  # 10MB
     SCREAMING_SNAKE_CASE	:			Optional[bool]							       =       None



class      a    (		datasets.ArrowBasedBuilder	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Tuple							       =       JsonConfig

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Dict:
          if self.config.block_size is not None:
               logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''      )
               __UpperCAmelCase     :			Tuple  							=      self.config.block_size
          if self.config.use_threads is not True:
               logger.warning(
                   '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'''      )
          if self.config.newlines_in_values is not None:
               raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported'''      )
          return datasets.DatasetInfo(features=self.config.features      )

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		Tuple      )						->							str:
          if not self.config.data_files:
               raise ValueError(f'At least one data file must be specified, but got data_files={self.config.data_files}'      )
          __UpperCAmelCase     :			Optional[int]  							=      dl_manager.download_and_extract(self.config.data_files      )
          if isinstance(snake_case							,			(str, list, tuple)      ):
               __UpperCAmelCase     :			Dict  							=      data_files
               if isinstance(snake_case							,			snake_case      ):
                    __UpperCAmelCase     :			List[Any]  							=      [files]
               __UpperCAmelCase     :			Tuple  							=      [dl_manager.iter_files(snake_case      ) for file in files]
               return [datasets.SplitGenerator(name=datasets.Split.TRAIN							,			gen_kwargs={'''files''': files}      )]
          __UpperCAmelCase     :			Tuple  							=      []
          for split_name, files in data_files.items():
               if isinstance(snake_case							,			snake_case      ):
                    __UpperCAmelCase     :			Any  							=      [files]
               __UpperCAmelCase     :			Optional[int]  							=      [dl_manager.iter_files(snake_case      ) for file in files]
               splits.append(datasets.SplitGenerator(name=snake_case							,			gen_kwargs={'''files''': files}      )      )
          return splits

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		pa.Table      )						->							pa.Table:
          if self.config.features is not None:
               # adding missing columns
               for column_name in set(self.config.features      ) - set(pa_table.column_names      ):
                    __UpperCAmelCase     :			Any  							=      self.config.features.arrow_schema.field(snake_case      ).type
                    __UpperCAmelCase     :			Dict  							=      pa_table.append_column(snake_case							,			pa.array([None] * len(snake_case      )							,			type=snake_case      )      )
               # more expensive cast to support nested structures with keys in a different order
               # allows str <-> int/float or str to Audio for example
               __UpperCAmelCase     :			Tuple  							=      table_cast(snake_case							,			self.config.features.arrow_schema      )
          return pa_table






     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		Any      )						->							Optional[int]:
          for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case      )      ):
               # If the file is one json object and if we need to look at the list of items in one specific field
               if self.config.field is not None:
                    with open(snake_case							,			encoding=self.config.encoding							,			errors=self.config.encoding_errors      ) as f:
                         __UpperCAmelCase     :			Optional[int]  							=      json.load(snake_case      )

                    # We keep only the field we are interested in
                    __UpperCAmelCase     :			int  							=      dataset[self.config.field]

                    # We accept two format: a list of dicts or a dict of lists
                    if isinstance(snake_case							,			(list, tuple)      ):
                         __UpperCAmelCase     :			Optional[Any]  							=      set().union(*[row.keys() for row in dataset]      )
                         __UpperCAmelCase     :			Union[str, Any]  							=      {col: [row.get(snake_case      ) for row in dataset] for col in keys}
                    else:
                         __UpperCAmelCase     :			Optional[int]  							=      dataset
                    __UpperCAmelCase     :			Tuple  							=      pa.Table.from_pydict(snake_case      )
                    yield file_idx, self._cast_table(snake_case      )

               # If the file has one json object per line
               else:
                    with open(snake_case							,			'''rb'''      ) as f:
                         __UpperCAmelCase     :			Optional[Any]  							=      0
                         # Use block_size equal to the chunk size divided by 32 to leverage multithreading
                         # Set a default minimum value of 16kB if the chunk size is really small
                         __UpperCAmelCase     :			int  							=      max(self.config.chunksize // 32							,			16 << 10      )
                         __UpperCAmelCase     :			Any  							=      (
                             self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
                         )
                         while True:
                              __UpperCAmelCase     :			List[Any]  							=      f.read(self.config.chunksize      )
                              if not batch:
                                   break
                              # Finish current line
                              try:
                                   batch += f.readline()
                              except (AttributeError, io.UnsupportedOperation):
                                   batch += readline(snake_case      )
                              # PyArrow only accepts utf-8 encoded bytes
                              if self.config.encoding != "utf-8":
                                   __UpperCAmelCase     :			Union[str, Any]  							=      batch.decode(self.config.encoding							,			errors=snake_case      ).encode('''utf-8'''      )
                              try:
                                   while True:
                                        try:
                                             __UpperCAmelCase     :			List[str]  							=      paj.read_json(
                                                 io.BytesIO(snake_case      )							,			read_options=paj.ReadOptions(block_size=snake_case      )      )
                                             break
                                        except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                                             if (
                                                 isinstance(snake_case							,			pa.ArrowInvalid      )
                                                 and "straddling" not in str(snake_case      )
                                                 or block_size > len(snake_case      )
                                             ):
                                                  raise
                                             else:
                                                  # Increase the block size in case it was too small.
                                                  # The block size will be reset for the next file.
                                                  logger.debug(
                                                      f'Batch of {len(snake_case      )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.'      )
                                                  block_size *= 2
                              except pa.ArrowInvalid as e:
                                   try:
                                        with open(
                                            snake_case							,			encoding=self.config.encoding							,			errors=self.config.encoding_errors      ) as f:
                                             __UpperCAmelCase     :			Optional[Any]  							=      json.load(snake_case      )
                                   except json.JSONDecodeError:
                                        logger.error(f'Failed to read file \'{file}\' with error {type(snake_case      )}: {e}'      )
                                        raise e
                                   # If possible, parse the file as a list of json objects and exit the loop
                                   if isinstance(snake_case							,			snake_case      ):  # list is the only sequence type supported in JSON
                                        try:
                                             __UpperCAmelCase     :			Dict  							=      set().union(*[row.keys() for row in dataset]      )
                                             __UpperCAmelCase     :			Optional[Any]  							=      {col: [row.get(snake_case      ) for row in dataset] for col in keys}
                                             __UpperCAmelCase     :			Union[str, Any]  							=      pa.Table.from_pydict(snake_case      )
                                        except (pa.ArrowInvalid, AttributeError) as e:
                                             logger.error(f'Failed to read file \'{file}\' with error {type(snake_case      )}: {e}'      )
                                             raise ValueError(f'Not able to read records in the JSON file at {file}.'      ) from None
                                        yield file_idx, self._cast_table(snake_case      )
                                        break
                                   else:
                                        logger.error(f'Failed to read file \'{file}\' with error {type(snake_case      )}: {e}'      )
                                        raise ValueError(
                                            f'Not able to read records in the JSON file at {file}. '
                                            f'You should probably indicate the field of the JSON file containing your records. '
                                            f'This JSON file contain the following fields: {str(list(dataset.keys()      )      )}. '
                                            f'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. '      ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                              yield (file_idx, batch_idx), self._cast_table(snake_case      )
                              batch_idx += 1