





"""simple docstring"""


import importlib
import inspect
import json
import os
from collections import OrderedDict

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


a__   :       int   						=			logging.get_logger(__name__)

a__   :       int   						=			OrderedDict(
    [
        ("""align""", """AlignProcessor"""),
        ("""altclip""", """AltCLIPProcessor"""),
        ("""bark""", """BarkProcessor"""),
        ("""blip""", """BlipProcessor"""),
        ("""blip-2""", """Blip2Processor"""),
        ("""bridgetower""", """BridgeTowerProcessor"""),
        ("""chinese_clip""", """ChineseCLIPProcessor"""),
        ("""clap""", """ClapProcessor"""),
        ("""clip""", """CLIPProcessor"""),
        ("""clipseg""", """CLIPSegProcessor"""),
        ("""flava""", """FlavaProcessor"""),
        ("""git""", """GitProcessor"""),
        ("""groupvit""", """CLIPProcessor"""),
        ("""hubert""", """Wav2Vec2Processor"""),
        ("""instructblip""", """InstructBlipProcessor"""),
        ("""layoutlmv2""", """LayoutLMv2Processor"""),
        ("""layoutlmv3""", """LayoutLMv3Processor"""),
        ("""markuplm""", """MarkupLMProcessor"""),
        ("""mctct""", """MCTCTProcessor"""),
        ("""mgp-str""", """MgpstrProcessor"""),
        ("""oneformer""", """OneFormerProcessor"""),
        ("""owlvit""", """OwlViTProcessor"""),
        ("""pix2struct""", """Pix2StructProcessor"""),
        ("""sam""", """SamProcessor"""),
        ("""sew""", """Wav2Vec2Processor"""),
        ("""sew-d""", """Wav2Vec2Processor"""),
        ("""speech_to_text""", """Speech2TextProcessor"""),
        ("""speech_to_text_2""", """Speech2Text2Processor"""),
        ("""speecht5""", """SpeechT5Processor"""),
        ("""trocr""", """TrOCRProcessor"""),
        ("""tvlt""", """TvltProcessor"""),
        ("""unispeech""", """Wav2Vec2Processor"""),
        ("""unispeech-sat""", """Wav2Vec2Processor"""),
        ("""vilt""", """ViltProcessor"""),
        ("""vision-text-dual-encoder""", """VisionTextDualEncoderProcessor"""),
        ("""wav2vec2""", """Wav2Vec2Processor"""),
        ("""wav2vec2-conformer""", """Wav2Vec2Processor"""),
        ("""wavlm""", """Wav2Vec2Processor"""),
        ("""whisper""", """WhisperProcessor"""),
        ("""xclip""", """XCLIPProcessor"""),
    ]
)

a__   :       List[str]   						=			_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)





def 							a__     (					_UpperCAmelCase		)      ->					List[Any]:

 '''simple docstring'''






 for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
  if class_name in processors:
   snake_case__      							=			model_type_to_module_name(_UpperCAmelCase		)

   snake_case__      							=			importlib.import_module(f".{module_name}"		,       "transformers.models"		)
   try:
    return getattr(_UpperCAmelCase		,       _UpperCAmelCase		)
   except AttributeError:
    continue

 for processor in PROCESSOR_MAPPING._extra_content.values():
  if getattr(_UpperCAmelCase		,       "__name__"		,       _UpperCAmelCase		) == class_name:
   return processor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
 snake_case__      							=			importlib.import_module("transformers"		)
 if hasattr(_UpperCAmelCase		,       _UpperCAmelCase		):
  return getattr(_UpperCAmelCase		,       _UpperCAmelCase		)

 return None



class        lowercase_			:

       def __init__(     self       ):






        '''simple docstring'''

        raise EnvironmentError(
            "AutoProcessor is designed to be instantiated "
            "using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."       )

       @classmethod
       @replace_list_option_in_docstrings(__SCREAMING_SNAKE_CASE       )
       def 						_SCREAMING_SNAKE_CASE(     cls				,   __SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       ):






        '''simple docstring'''

        snake_case__      							=			kwargs.pop("config"				,   __SCREAMING_SNAKE_CASE       )
        snake_case__      							=			kwargs.pop("trust_remote_code"				,   __SCREAMING_SNAKE_CASE       )
        snake_case__      							=			True

        snake_case__      							=			None
        snake_case__      							=			None

        # First, let's see if we have a preprocessor config.
        # Filter the kwargs for `get_file_from_repo`.
        snake_case__      							=			{
            key: kwargs[key] for key in inspect.signature(__SCREAMING_SNAKE_CASE       ).parameters.keys() if key in kwargs
        }
        # Let's start by checking whether the processor class is saved in an image processor
        snake_case__      							=			get_file_from_repo(
            __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
        if preprocessor_config_file is not None:
         snake_case__							,				snake_case__      							=			ImageProcessingMixin.get_image_processor_dict(__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
         snake_case__      							=			config_dict.get("processor_class"				,   __SCREAMING_SNAKE_CASE       )
         if "AutoProcessor" in config_dict.get("auto_map"				,   {}       ):
          snake_case__      							=			config_dict["auto_map"]["AutoProcessor"]

        # If not found, let's check whether the processor class is saved in a feature extractor config
        if preprocessor_config_file is not None and processor_class is None:
         snake_case__							,				snake_case__      							=			FeatureExtractionMixin.get_feature_extractor_dict(__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
         snake_case__      							=			config_dict.get("processor_class"				,   __SCREAMING_SNAKE_CASE       )
         if "AutoProcessor" in config_dict.get("auto_map"				,   {}       ):
          snake_case__      							=			config_dict["auto_map"]["AutoProcessor"]

        if processor_class is None:
         # Next, let's check whether the processor class is saved in a tokenizer
         snake_case__      							=			get_file_from_repo(
             __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
         if tokenizer_config_file is not None:
          with open(__SCREAMING_SNAKE_CASE				,   encoding="utf-8"       ) as reader:
           snake_case__      							=			json.load(__SCREAMING_SNAKE_CASE       )

          snake_case__      							=			config_dict.get("processor_class"				,   __SCREAMING_SNAKE_CASE       )
          if "AutoProcessor" in config_dict.get("auto_map"				,   {}       ):
           snake_case__      							=			config_dict["auto_map"]["AutoProcessor"]

        if processor_class is None:
         # Otherwise, load config, if it can be loaded.
         if not isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
          snake_case__      							=			AutoConfig.from_pretrained(
              __SCREAMING_SNAKE_CASE				,   trust_remote_code=__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )

         # And check if the config contains the processor class.
         snake_case__      							=			getattr(__SCREAMING_SNAKE_CASE				,   "processor_class"				,   __SCREAMING_SNAKE_CASE       )
         if hasattr(__SCREAMING_SNAKE_CASE				,   "auto_map"       ) and "AutoProcessor" in config.auto_map:
          snake_case__      							=			config.auto_map["AutoProcessor"]

        if processor_class is not None:
         snake_case__      							=			processor_class_from_name(__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			processor_auto_map is not None
        snake_case__      							=			processor_class is not None or type(__SCREAMING_SNAKE_CASE       ) in PROCESSOR_MAPPING
        snake_case__      							=			resolve_trust_remote_code(
            __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

        if has_remote_code and trust_remote_code:
         snake_case__      							=			get_class_from_dynamic_module(
             __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
         snake_case__      							=			kwargs.pop("code_revision"				,   __SCREAMING_SNAKE_CASE       )
         if os.path.isdir(__SCREAMING_SNAKE_CASE       ):
          processor_class.register_for_auto_class()
         return processor_class.from_pretrained(
             __SCREAMING_SNAKE_CASE				,   trust_remote_code=__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
        elif processor_class is not None:
         return processor_class.from_pretrained(
             __SCREAMING_SNAKE_CASE				,   trust_remote_code=__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
        # Last try: we use the PROCESSOR_MAPPING.
        elif type(__SCREAMING_SNAKE_CASE       ) in PROCESSOR_MAPPING:
         return PROCESSOR_MAPPING[type(__SCREAMING_SNAKE_CASE       )].from_pretrained(__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )

        # At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
        # tokenizer.
        try:
         return AutoTokenizer.from_pretrained(
             __SCREAMING_SNAKE_CASE				,   trust_remote_code=__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
        except Exception:
         try:
          return AutoImageProcessor.from_pretrained(
              __SCREAMING_SNAKE_CASE				,   trust_remote_code=__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
         except Exception:
          pass

         try:
          return AutoFeatureExtractor.from_pretrained(
              __SCREAMING_SNAKE_CASE				,   trust_remote_code=__SCREAMING_SNAKE_CASE				,   **__SCREAMING_SNAKE_CASE       )
         except Exception:
          pass

        raise ValueError(
            F"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a "
            "tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains"
            "the files of at least one of those processing classes."       )

       @staticmethod
       def 						_SCREAMING_SNAKE_CASE(     __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):






        '''simple docstring'''

        PROCESSOR_MAPPING.register(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )








"""simple docstring"""


import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


a__   :       Optional[Any]   						=			logging.get_logger(__name__)  # pylint: disable=invalid-name

a__   :       Tuple   						=			"""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""



@dataclass
class        lowercase_			(       __lowerCAmelCase							):
       snake_case__			:							Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]



class        lowercase_			(       __lowerCAmelCase							):

       def __init__(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   ):






        '''simple docstring'''

        super().__init__()

        self.register_modules(
            prior=__SCREAMING_SNAKE_CASE				,   text_encoder=__SCREAMING_SNAKE_CASE				,   tokenizer=__SCREAMING_SNAKE_CASE				,   scheduler=__SCREAMING_SNAKE_CASE				,   renderer=__SCREAMING_SNAKE_CASE				,   )

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):






        '''simple docstring'''

        if latents is None:
         snake_case__      							=			randn_tensor(__SCREAMING_SNAKE_CASE				,   generator=__SCREAMING_SNAKE_CASE				,   device=__SCREAMING_SNAKE_CASE				,   dtype=__SCREAMING_SNAKE_CASE       )
        else:
         if latents.shape != shape:
          raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"       )
         snake_case__      							=			latents.to(__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			latents * scheduler.init_noise_sigma
        return latents

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

        if is_accelerate_available():
         from accelerate import cpu_offload
        else:
         raise ImportError("Please install accelerate via `pip install accelerate`"       )

        snake_case__      							=			torch.device(F"cuda:{gpu_id}"       )

        snake_case__      							=			[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
         if cpu_offloaded_model is not None:
          cpu_offload(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

        if is_accelerate_available() and is_accelerate_version(">="				,   "0.17.0.dev0"       ):
         from accelerate import cpu_offload_with_hook
        else:
         raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."       )

        snake_case__      							=			torch.device(F"cuda:{gpu_id}"       )

        if self.device.type != "cpu":
         self.to("cpu"				,   silence_dtype_warnings=__SCREAMING_SNAKE_CASE       )
         torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        snake_case__      							=			None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
         snake_case__							,				snake_case__      							=			cpu_offload_with_hook(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   prev_module_hook=__SCREAMING_SNAKE_CASE       )

        if self.safety_checker is not None:
         snake_case__							,				snake_case__      							=			cpu_offload_with_hook(self.safety_checker				,   __SCREAMING_SNAKE_CASE				,   prev_module_hook=__SCREAMING_SNAKE_CASE       )

        # We'll offload the last model manually.
        snake_case__      							=			hook

       @property
       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        if self.device != torch.device("meta"       ) or not hasattr(self.text_encoder				,   "_hf_hook"       ):
         return self.device
        for module in self.text_encoder.modules():
         if (
             hasattr(__SCREAMING_SNAKE_CASE				,   "_hf_hook"       )
             and hasattr(module._hf_hook				,   "execution_device"       )
             and module._hf_hook.execution_device is not None
         ):
          return torch.device(module._hf_hook.execution_device       )
        return self.device

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   ):






        '''simple docstring'''

        len(__SCREAMING_SNAKE_CASE       ) if isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        snake_case__      							=			0
        # get prompt text embeddings
        snake_case__      							=			self.tokenizer(
            __SCREAMING_SNAKE_CASE				,   padding="max_length"				,   max_length=self.tokenizer.model_max_length				,   truncation=__SCREAMING_SNAKE_CASE				,   return_tensors="pt"				,   )
        snake_case__      							=			text_inputs.input_ids
        snake_case__      							=			self.tokenizer(__SCREAMING_SNAKE_CASE				,   padding="longest"				,   return_tensors="pt"       ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]       )
         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}"       )

        snake_case__      							=			self.text_encoder(text_input_ids.to(__SCREAMING_SNAKE_CASE       )       )
        snake_case__      							=			text_encoder_output.text_embeds

        snake_case__      							=			prompt_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE				,   dim=0       )
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        snake_case__      							=			prompt_embeds / torch.linalg.norm(__SCREAMING_SNAKE_CASE				,   dim=-1				,   keepdim=__SCREAMING_SNAKE_CASE       )

        if do_classifier_free_guidance:
         snake_case__      							=			torch.zeros_like(__SCREAMING_SNAKE_CASE       )

         # 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
         snake_case__      							=			torch.cat([negative_prompt_embeds, prompt_embeds]       )

        # Rescale the features to have unit variance
        snake_case__      							=			math.sqrt(prompt_embeds.shape[1]       ) * prompt_embeds

        return prompt_embeds

       @torch.no_grad()
       @replace_example_docstring(__SCREAMING_SNAKE_CASE       )
       def __call__(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE = 1				,   __SCREAMING_SNAKE_CASE = 25				,   __SCREAMING_SNAKE_CASE = None				,   __SCREAMING_SNAKE_CASE = None				,   __SCREAMING_SNAKE_CASE = 4.0				,   __SCREAMING_SNAKE_CASE = 64				,   __SCREAMING_SNAKE_CASE = "pil"				,   __SCREAMING_SNAKE_CASE = True				,   ):






        '''simple docstring'''

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

        snake_case__      							=			self._execution_device

        snake_case__      							=			batch_size * num_images_per_prompt

        snake_case__      							=			guidance_scale > 1.0
        snake_case__      							=			self._encode_prompt(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

        # prior

        self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE				,   device=__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			self.scheduler.timesteps

        snake_case__      							=			self.prior.config.num_embeddings
        snake_case__      							=			self.prior.config.embedding_dim

        snake_case__      							=			self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)				,   prompt_embeds.dtype				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   self.scheduler				,   )

        # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
        snake_case__      							=			latents.reshape(latents.shape[0]				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

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

         snake_case__      							=			self.prior(
             __SCREAMING_SNAKE_CASE				,   timestep=__SCREAMING_SNAKE_CASE				,   proj_embedding=__SCREAMING_SNAKE_CASE				,   ).predicted_image_embedding

         # remove the variance
         snake_case__							,				snake_case__      							=			noise_pred.split(
             scaled_model_input.shape[2]				,   dim=2       )  # batch_size, num_embeddings, embedding_dim

         if do_classifier_free_guidance is not None:
          snake_case__							,				snake_case__      							=			noise_pred.chunk(2       )
          snake_case__      							=			noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

         snake_case__      							=			self.scheduler.step(
             __SCREAMING_SNAKE_CASE				,   timestep=__SCREAMING_SNAKE_CASE				,   sample=__SCREAMING_SNAKE_CASE				,   ).prev_sample

        if output_type == "latent":
         return ShapEPipelineOutput(images=__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			[]
        for i, latent in enumerate(__SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			self.renderer.decode(
             latent[None, :]				,   __SCREAMING_SNAKE_CASE				,   size=__SCREAMING_SNAKE_CASE				,   ray_batch_size=4096				,   n_coarse_samples=64				,   n_fine_samples=128				,   )
         images.append(__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			torch.stack(__SCREAMING_SNAKE_CASE       )

        if output_type not in ["np", "pil"]:
         raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"       )

        snake_case__      							=			images.cpu().numpy()

        if output_type == "pil":
         snake_case__      							=			[self.numpy_to_pil(__SCREAMING_SNAKE_CASE       ) for image in images]

        # Offload last model to CPU
        if hasattr(self				,   "final_offload_hook"       ) and self.final_offload_hook is not None:
         self.final_offload_hook.offload()

        if not return_dict:
         return (images,)

        return ShapEPipelineOutput(images=__SCREAMING_SNAKE_CASE       )

