




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


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

A_      =    '''
    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  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = 42







class  lowercase(					__a			):







 '''simple docstring'''





 def __init__(    self:		List[str],				a_:		PriorTransformer,				a_:		CLIPVisionModel,				a_:		CLIPImageProcessor,				a_:		HeunDiscreteScheduler,				a_:		ShapERenderer,				):




   '''simple docstring'''



   super().__init__()

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


 def 			UpperCamelCase_       (    self:		Any,				a_:		Tuple,				a_:		Tuple,				a_:		List[str],				a_:		List[Any],				a_:		List[Any],				a_:		Union[str, Any]		):




   '''simple docstring'''



   if latents is None:
     _snake_case							:		List[Any]								=  randn_tensor(a_,				generator=a_,				device=a_,				dtype=a_		)
   else:
     if latents.shape != shape:
       raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"		)
     _snake_case							:		Optional[int]								=  latents.to(a_		)

   _snake_case							:		Any								=  latents * scheduler.init_noise_sigma
   return latents


 def 			UpperCamelCase_       (    self:		Optional[Any],				a_:		List[Any]=0		):




   '''simple docstring'''



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

   _snake_case							:		int								=  torch.device(f"cuda:{gpu_id}"		)

   _snake_case							:		Union[str, Any]								=  [self.image_encoder, self.prior]
   for cpu_offloaded_model in models:
     if cpu_offloaded_model is not None:
       cpu_offload(a_,				a_		)


 @property
 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



   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(a_,				"""_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:		Union[str, Any],				a_:		Optional[int],				a_:		str,				a_:		Dict,				a_:		int,				):




   '''simple docstring'''



   if isinstance(a_,				a_		) and isinstance(image[0],				torch.Tensor		):
     _snake_case							:		Optional[Any]								=  torch.cat(a_,				axis=0		) if image[0].ndim == 4 else torch.stack(a_,				axis=0		)

   if not isinstance(a_,				torch.Tensor		):
     _snake_case							:		List[str]								=  self.image_processor(a_,				return_tensors="""pt"""		).pixel_values[0].unsqueeze(0		)

   _snake_case							:		Optional[int]								=  image.to(dtype=self.image_encoder.dtype,				device=a_		)

   _snake_case							:		List[str]								=  self.image_encoder(a_		)["""last_hidden_state"""]
   _snake_case							:		List[Any]								=  image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

   _snake_case							:		Any								=  image_embeds.repeat_interleave(a_,				dim=0		)

   if do_classifier_free_guidance:
     _snake_case							:		int								=  torch.zeros_like(a_		)

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

   return image_embeds


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




   '''simple docstring'''



   if isinstance(a_,				PIL.Image.Image		):
     _snake_case							:		Optional[int]								=  1
   elif isinstance(a_,				torch.Tensor		):
     _snake_case							:		List[Any]								=  image.shape[0]
   elif isinstance(a_,				a_		) and isinstance(image[0],				(torch.Tensor, PIL.Image.Image)		):
     _snake_case							:		Optional[Any]								=  len(a_		)
   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(a_		)}"		)

   _snake_case							:		Tuple								=  self._execution_device

   _snake_case							:		str								=  batch_size * num_images_per_prompt

   _snake_case							:		Tuple								=  guidance_scale > 1.0
   _snake_case							:		Any								=  self._encode_image(a_,				a_,				a_,				a_		)

   # prior

   self.scheduler.set_timesteps(a_,				device=a_		)
   _snake_case							:		Optional[int]								=  self.scheduler.timesteps

   _snake_case							:		Optional[int]								=  self.prior.config.num_embeddings
   _snake_case							:		List[str]								=  self.prior.config.embedding_dim

   _snake_case							:		Optional[Any]								=  self.prepare_latents(
       (batch_size, num_embeddings * embedding_dim),				image_embeds.dtype,				a_,				a_,				a_,				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							:		Optional[int]								=  latents.reshape(latents.shape[0],				a_,				a_		)

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

     _snake_case							:		Dict								=  self.prior(
         a_,				timestep=a_,				proj_embedding=a_,				).predicted_image_embedding

     # remove the variance
     _snake_case		, _snake_case							:		Tuple								=  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							:		Dict								=  noise_pred.chunk(2		)
       _snake_case							:		int								=  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

     _snake_case							:		Optional[int]								=  self.scheduler.step(
         a_,				timestep=a_,				sample=a_,				).prev_sample

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

   _snake_case							:		List[str]								=  []
   for i, latent in enumerate(a_		):
     print()
     _snake_case							:		str								=  self.renderer.decode(
         latent[None, :],				a_,				size=a_,				ray_batch_size=4_096,				n_coarse_samples=64,				n_fine_samples=128,				)

     images.append(a_		)

   _snake_case							:		Optional[int]								=  torch.stack(a_		)

   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							:		List[Any]								=  images.cpu().numpy()

   if output_type == "pil":
     _snake_case							:		str								=  [self.numpy_to_pil(a_		) 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=a_		)








"""simple docstring"""


import unittest

from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


A_      =    get_tests_dir('''fixtures/spiece.model''')






@require_sentencepiece
@require_tokenizers
class  lowercase(					__a	,      unittest.TestCase			):







 '''simple docstring'''





 lowercase__			 = AlbertTokenizer
 lowercase__			 = AlbertTokenizerFast
 lowercase__			 = True
 lowercase__			 = True
 lowercase__			 = True


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   super().setUp()

   # We have a SentencePiece fixture for testing
   _snake_case							:		Optional[int]								=  AlbertTokenizer(a_		)
   tokenizer.save_pretrained(self.tmpdirname		)


 def 			UpperCamelCase_       (    self:		Optional[int],				a_:		int		):




   '''simple docstring'''



   _snake_case							:		Dict								=  """this is a test"""
   _snake_case							:		Optional[int]								=  """this is a test"""
   return input_text, output_text


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		str								=  """<pad>"""
   _snake_case							:		List[Any]								=  0

   self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_		),				a_		)
   self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_		),				a_		)


 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  list(self.get_tokenizer().get_vocab().keys()		)

   self.assertEqual(vocab_keys[0],				"""<pad>"""		)
   self.assertEqual(vocab_keys[1],				"""<unk>"""		)
   self.assertEqual(vocab_keys[-1],				"""▁eloquent"""		)
   self.assertEqual(len(a_		),				30_000		)


 def 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   self.assertEqual(self.get_tokenizer().vocab_size,				30_000		)


 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   if not self.test_rust_tokenizer:
     return

   _snake_case							:		Tuple								=  self.get_tokenizer()
   _snake_case							:		List[str]								=  self.get_rust_tokenizer()

   _snake_case							:		Optional[int]								=  """I was born in 92000, and this is falsé."""

   _snake_case							:		Optional[Any]								=  tokenizer.tokenize(a_		)
   _snake_case							:		List[str]								=  rust_tokenizer.tokenize(a_		)
   self.assertListEqual(a_,				a_		)

   _snake_case							:		Any								=  tokenizer.encode(a_,				add_special_tokens=a_		)
   _snake_case							:		Any								=  rust_tokenizer.encode(a_,				add_special_tokens=a_		)
   self.assertListEqual(a_,				a_		)

   _snake_case							:		int								=  self.get_rust_tokenizer()
   _snake_case							:		Dict								=  tokenizer.encode(a_		)
   _snake_case							:		Optional[int]								=  rust_tokenizer.encode(a_		)
   self.assertListEqual(a_,				a_		)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		Any								=  AlbertTokenizer(a_,				keep_accents=a_		)

   _snake_case							:		Any								=  tokenizer.tokenize("""This is a test"""		)
   self.assertListEqual(a_,				["""▁this""", """▁is""", """▁a""", """▁test"""]		)

   self.assertListEqual(tokenizer.convert_tokens_to_ids(a_		),				[48, 25, 21, 1_289]		)

   _snake_case							:		Dict								=  tokenizer.tokenize("""I was born in 92000, and this is falsé."""		)
   self.assertListEqual(
       a_,				["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""]		)
   _snake_case							:		str								=  tokenizer.convert_tokens_to_ids(a_		)
   self.assertListEqual(a_,				[31, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9]		)

   _snake_case							:		Tuple								=  tokenizer.convert_ids_to_tokens(a_		)
   self.assertListEqual(
       a_,				["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""],				)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  AlbertTokenizer(a_		)

   _snake_case							:		int								=  tokenizer.encode("""sequence builders"""		)
   _snake_case							:		Optional[int]								=  tokenizer.encode("""multi-sequence build"""		)

   _snake_case							:		Any								=  tokenizer.build_inputs_with_special_tokens(a_		)
   _snake_case							:		Union[str, Any]								=  tokenizer.build_inputs_with_special_tokens(a_,				a_		)

   assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
   assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
       tokenizer.sep_token_id
   ]


 @slow
 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   _snake_case							:		Any								=  {"""attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """input_ids""": [[2, 21_970, 13, 5, 6_092, 167, 28, 7_103, 2_153, 673, 8, 7_028, 12_051, 18, 17, 7_103, 2_153, 673, 8, 3_515, 18_684, 8, 4_461, 6, 1_927, 297, 8, 12_060, 2_607, 18, 13, 5, 4_461, 15, 10_538, 38, 8, 135, 15, 822, 58, 15, 993, 10_363, 15, 1_460, 8_005, 4_461, 15, 993, 255, 2_328, 9, 9, 9, 6, 26, 1_112, 816, 3_260, 13, 5, 103, 2_377, 6, 17, 1_112, 816, 2_782, 13, 5, 103, 10_641, 6, 29, 84, 2_512, 2_430, 782, 18_684, 2_761, 19, 808, 2_430, 2_556, 17, 855, 1_480, 9_477, 4_091, 128, 11_712, 15, 7_103, 2_153, 673, 17, 24_883, 9_990, 9, 3], [2, 11_502, 25, 1_006, 20, 782, 8, 11_809, 855, 1_732, 19_393, 18_667, 37, 367, 21_018, 69, 1_854, 34, 11_860, 19_124, 27, 156, 225, 17, 193, 4_141, 19, 65, 9_124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2_231, 886, 2_385, 17_659, 84, 14, 16_792, 1_952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
   # fmt: on

   self.tokenizer_integration_test_util(
       expected_encoding=a_,				model_name="""albert-base-v2""",				revision="""6b6560eaf5ff2e250b00c50f380c5389a9c2d82e""",				)


