






"""simple docstring"""





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

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

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


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

_SCREAMING_SNAKE_CASE   :							int          =		'''
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

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

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

        >>> guidance_scale = 3.0
        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"
        >>> image = load_image(image_url).convert("RGB")

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

        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")
        ```
'''






@dataclass
class 	a		(   __snake_case						):
    SCREAMING_SNAKE_CASE		:	Union[PIL.Image.Image, np.ndarray]






class 	a		(   __snake_case						):






    def __init__(			self	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				PriorTransformer			,		__SCREAMING_SNAKE_CASE	:				CLIPVisionModel			,		__SCREAMING_SNAKE_CASE	:				CLIPImageProcessor			,		__SCREAMING_SNAKE_CASE	:				HeunDiscreteScheduler			,		__SCREAMING_SNAKE_CASE	:				ShapERenderer			,		)	->						Union[str, Any]:
      super().__init__()

      self.register_modules(
          prior=__SCREAMING_SNAKE_CASE			,		image_encoder=__SCREAMING_SNAKE_CASE			,		image_processor=__SCREAMING_SNAKE_CASE			,		scheduler=__SCREAMING_SNAKE_CASE			,		renderer=__SCREAMING_SNAKE_CASE			,		)






    def   UpperCamelCase			(			self	:				Any			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Dict			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				List[str]			,		__SCREAMING_SNAKE_CASE	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				Optional[int]   )	->						int:
      if latents is None:
        lowerCamelCase_       	=		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}'''   )
        lowerCamelCase_       	=		latents.to(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		latents * scheduler.init_noise_sigma
      return latents






    def   UpperCamelCase			(			self	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				int=0   )	->						Optional[int]:
      if is_accelerate_available():
        from accelerate import cpu_offload
      else:
        raise ImportError('Please install accelerate via `pip install accelerate`'   )

      lowerCamelCase_       	=		torch.device(F'''cuda:{gpu_id}'''   )

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






    @property
    def   UpperCamelCase			(			self	:				Dict   )	->						Any:
      if self.device != torch.device('meta'   ) or not hasattr(self.image_encoder			,		'_hf_hook'   ):
        return self.device
      for module in self.image_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   UpperCamelCase			(			self	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Any			,		__SCREAMING_SNAKE_CASE	:				List[str]			,		)	->						int:
      if isinstance(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   ) and isinstance(image[0]			,		torch.Tensor   ):
        lowerCamelCase_       	=		torch.cat(__SCREAMING_SNAKE_CASE			,		axis=0   ) if image[0].ndim == 4 else torch.stack(__SCREAMING_SNAKE_CASE			,		axis=0   )

      if not isinstance(__SCREAMING_SNAKE_CASE			,		torch.Tensor   ):
        lowerCamelCase_       	=		self.image_processor(__SCREAMING_SNAKE_CASE			,		return_tensors='pt'   ).pixel_values[0].unsqueeze(0   )

      lowerCamelCase_       	=		image.to(dtype=self.image_encoder.dtype			,		device=__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.image_encoder(__SCREAMING_SNAKE_CASE   )['last_hidden_state']
      lowerCamelCase_       	=		image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

      lowerCamelCase_       	=		image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE			,		dim=0   )

      if do_classifier_free_guidance:
        lowerCamelCase_       	=		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
        lowerCamelCase_       	=		torch.cat([negative_image_embeds, image_embeds]   )

      return image_embeds






    @torch.no_grad()
    @replace_example_docstring(__SCREAMING_SNAKE_CASE   )
    def __call__(			self	:				List[str]			,		__SCREAMING_SNAKE_CASE	:				Union[PIL.Image.Image, List[PIL.Image.Image]]			,		__SCREAMING_SNAKE_CASE	:				int = 1			,		__SCREAMING_SNAKE_CASE	:				int = 25			,		__SCREAMING_SNAKE_CASE	:				Optional[Union[torch.Generator, List[torch.Generator]]] = None			,		__SCREAMING_SNAKE_CASE	:				Optional[torch.FloatTensor] = None			,		__SCREAMING_SNAKE_CASE	:				float = 4.0			,		__SCREAMING_SNAKE_CASE	:				int = 64			,		__SCREAMING_SNAKE_CASE	:				Optional[str] = "pil"			,		__SCREAMING_SNAKE_CASE	:				bool = True			,		)	->						List[Any]:

      if isinstance(__SCREAMING_SNAKE_CASE			,		PIL.Image.Image   ):
        lowerCamelCase_       	=		1
      elif isinstance(__SCREAMING_SNAKE_CASE			,		torch.Tensor   ):
        lowerCamelCase_       	=		image.shape[0]
      elif isinstance(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   ) and isinstance(image[0]			,		(torch.Tensor, PIL.Image.Image)   ):
        lowerCamelCase_       	=		len(__SCREAMING_SNAKE_CASE   )
      else:
        raise ValueError(
            F'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__SCREAMING_SNAKE_CASE   )}'''   )

      lowerCamelCase_       	=		self._execution_device

      lowerCamelCase_       	=		batch_size * num_images_per_prompt

      lowerCamelCase_       	=		guidance_scale > 1.0
      lowerCamelCase_       	=		self._encode_image(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

      # prior

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

      lowerCamelCase_       	=		self.prior.config.num_embeddings
      lowerCamelCase_       	=		self.prior.config.embedding_dim

      lowerCamelCase_       	=		self.prepare_latents(
          (batch_size, num_embeddings * embedding_dim)			,		image_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
      lowerCamelCase_       	=		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
        lowerCamelCase_       	=		torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
        lowerCamelCase_       	=		self.scheduler.scale_model_input(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

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

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

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

        lowerCamelCase_       	=		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   )

      lowerCamelCase_       	=		[]
      for i, latent in enumerate(__SCREAMING_SNAKE_CASE   ):
        print()
        lowerCamelCase_       	=		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   )

      lowerCamelCase_       	=		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}'''   )

      lowerCamelCase_       	=		images.cpu().numpy()

      if output_type == "pil":
        lowerCamelCase_       	=		[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   )












"""simple docstring"""





import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow






@is_pipeline_test
@require_torch
class 	a		(   unittest.TestCase						):






    @require_torch
    def   UpperCamelCase			(			self	:				str   )	->						str:
      lowerCamelCase_       	=		pipeline(
          task='zero-shot-audio-classification'			,		model='hf-internal-testing/tiny-clap-htsat-unfused'   )
      lowerCamelCase_       	=		load_dataset('ashraq/esc50'   )
      lowerCamelCase_       	=		dataset['train']['audio'][-1]['array']
      lowerCamelCase_       	=		audio_classifier(__SCREAMING_SNAKE_CASE			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']   )
      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}]			,		)






    @unittest.skip('No models are available in TF'   )
    def   UpperCamelCase			(			self	:				Tuple   )	->						Optional[Any]:
      pass






    @slow
    @require_torch
    def   UpperCamelCase			(			self	:				Optional[Any]   )	->						Optional[Any]:
      lowerCamelCase_       	=		pipeline(
          task='zero-shot-audio-classification'			,		model='laion/clap-htsat-unfused'			,		)
      # This is an audio of a dog
      lowerCamelCase_       	=		load_dataset('ashraq/esc50'   )
      lowerCamelCase_       	=		dataset['train']['audio'][-1]['array']
      lowerCamelCase_       	=		audio_classifier(__SCREAMING_SNAKE_CASE			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']   )

      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[
              {'score': 0.999, 'label': 'Sound of a dog'},
              {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
          ]			,		)

      lowerCamelCase_       	=		audio_classifier([audio] * 5			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']   )
      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[
              [
                  {'score': 0.999, 'label': 'Sound of a dog'},
                  {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
              ],
          ]
          * 5			,		)
      lowerCamelCase_       	=		audio_classifier(
          [audio] * 5			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']			,		batch_size=5   )
      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[
              [
                  {'score': 0.999, 'label': 'Sound of a dog'},
                  {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
              ],
          ]
          * 5			,		)






    @unittest.skip('No models are available in TF'   )
    def   UpperCamelCase			(			self	:				Optional[int]   )	->						int:
      pass




