

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


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

lowercase_   							=  '\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'





@dataclass
class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):
  _a		     =    42





class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):




  def __init__(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  )    ->					Any:
        '''simple docstring'''






        super().__init__()

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




  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Dict:
        '''simple docstring'''






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

        _lowercase      			=latents * scheduler.init_noise_sigma
        return latents




  def     A__	(							self				,  lowerCAmelCase=0   )    ->					int:
        '''simple docstring'''






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

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

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




  @property
  def     A__	(							self   )    ->					List[Any]:
        '''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(lowerCAmelCase				,  '_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     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  )    ->					int:
        '''simple docstring'''






        if isinstance(lowerCAmelCase				,  lowerCAmelCase   ) and isinstance(image[0]				,  torch.Tensor   ):
              _lowercase      			=torch.cat(lowerCAmelCase				,  axis=0   ) if image[0].ndim == 4 else torch.stack(lowerCAmelCase				,  axis=0   )

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

        _lowercase      			=image.to(dtype=self.image_encoder.dtype				,  device=lowerCAmelCase   )

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

        _lowercase      			=image_embeds.repeat_interleave(lowerCAmelCase				,  dim=0   )

        if do_classifier_free_guidance:
              _lowercase      			=torch.zeros_like(lowerCAmelCase   )

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

        return image_embeds




  @torch.no_grad()
  @replace_example_docstring(lowerCAmelCase   )
  def __call__(							self				,  lowerCAmelCase				,  lowerCAmelCase = 1				,  lowerCAmelCase = 25				,  lowerCAmelCase = None				,  lowerCAmelCase = None				,  lowerCAmelCase = 4.0				,  lowerCAmelCase = 64				,  lowerCAmelCase = "pil"				,  lowerCAmelCase = True				,  )    ->					Union[str, Any]:
        '''simple docstring'''






        if isinstance(lowerCAmelCase				,  PIL.Image.Image   ):
              _lowercase      			=1
        elif isinstance(lowerCAmelCase				,  torch.Tensor   ):
              _lowercase      			=image.shape[0]
        elif isinstance(lowerCAmelCase				,  lowerCAmelCase   ) and isinstance(image[0]				,  (torch.Tensor, PIL.Image.Image)   ):
              _lowercase      			=len(lowerCAmelCase   )
        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(lowerCAmelCase   )}'''   )

        _lowercase      			=self._execution_device

        _lowercase      			=batch_size * num_images_per_prompt

        _lowercase      			=guidance_scale > 1.0
        _lowercase      			=self._encode_image(lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase   )

        # prior

        self.scheduler.set_timesteps(lowerCAmelCase				,  device=lowerCAmelCase   )
        _lowercase      			=self.scheduler.timesteps

        _lowercase      			=self.prior.config.num_embeddings
        _lowercase      			=self.prior.config.embedding_dim

        _lowercase      			=self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)				,  image_embeds.dtype				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  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
        _lowercase      			=latents.reshape(latents.shape[0]				,  lowerCAmelCase				,  lowerCAmelCase   )

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

              _lowercase      			=self.prior(
                  lowerCAmelCase				,  timestep=lowerCAmelCase				,  proj_embedding=lowerCAmelCase				,  ).predicted_image_embedding

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

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

              _lowercase      			=self.scheduler.step(
                  lowerCAmelCase				,  timestep=lowerCAmelCase				,  sample=lowerCAmelCase				,  ).prev_sample

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

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

              images.append(lowerCAmelCase   )

        _lowercase      			=torch.stack(lowerCAmelCase   )

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

        _lowercase      			=images.cpu().numpy()

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





import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
  from PIL import Image

  from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor





@require_vision
class 					__lowerCAmelCase	(   unittest.TestCase				):




  def     A__	(							self   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=tempfile.mkdtemp()

        _lowercase      			=[
            '[UNK]',
            '[CLS]',
            '[SEP]',
            '[PAD]',
            '[MASK]',
            '的',
            '价',
            '格',
            '是',
            '15',
            '便',
            'alex',
            '##andra',
            '，',
            '。',
            '-',
            't',
            'shirt',
        ]
        _lowercase      			=os.path.join(self.tmpdirname				,  VOCAB_FILES_NAMES['vocab_file']   )
        with open(self.vocab_file				,  'w'				,  encoding='utf-8'   ) as vocab_writer:
              vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]   )   )

        _lowercase      			={
            'do_resize': True,
            'size': {'height': 224, 'width': 224},
            'do_center_crop': True,
            'crop_size': {'height': 18, 'width': 18},
            'do_normalize': True,
            'image_mean': [0.48145466, 0.4578275, 0.40821073],
            'image_std': [0.26862954, 0.26130258, 0.27577711],
            'do_convert_rgb': True,
        }
        _lowercase      			=os.path.join(self.tmpdirname				,  lowerCAmelCase   )
        with open(self.image_processor_file				,  'w'				,  encoding='utf-8'   ) as fp:
              json.dump(lowerCAmelCase				,  lowerCAmelCase   )




  def     A__	(							self				,  **lowerCAmelCase   )    ->					Optional[int]:
        '''simple docstring'''






        return BertTokenizer.from_pretrained(self.tmpdirname				,  **lowerCAmelCase   )




  def     A__	(							self				,  **lowerCAmelCase   )    ->					Optional[Any]:
        '''simple docstring'''






        return BertTokenizerFast.from_pretrained(self.tmpdirname				,  **lowerCAmelCase   )




  def     A__	(							self				,  **lowerCAmelCase   )    ->					Any:
        '''simple docstring'''






        return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname				,  **lowerCAmelCase   )




  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        shutil.rmtree(self.tmpdirname   )




  def     A__	(							self   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=[np.random.randint(255				,  size=(3, 30, 400)				,  dtype=np.uinta   )]

        _lowercase      			=[Image.fromarray(np.moveaxis(lowerCAmelCase				,  0				,  -1   )   ) for x in image_inputs]

        return image_inputs




  def     A__	(							self   )    ->					str:
        '''simple docstring'''






        _lowercase      			=self.get_tokenizer()
        _lowercase      			=self.get_rust_tokenizer()
        _lowercase      			=self.get_image_processor()

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )
        processor_slow.save_pretrained(self.tmpdirname   )
        _lowercase      			=ChineseCLIPProcessor.from_pretrained(self.tmpdirname				,  use_fast=lowerCAmelCase   )

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )
        processor_fast.save_pretrained(self.tmpdirname   )
        _lowercase      			=ChineseCLIPProcessor.from_pretrained(self.tmpdirname   )

        self.assertEqual(processor_slow.tokenizer.get_vocab()				,  tokenizer_slow.get_vocab()   )
        self.assertEqual(processor_fast.tokenizer.get_vocab()				,  tokenizer_fast.get_vocab()   )
        self.assertEqual(tokenizer_slow.get_vocab()				,  tokenizer_fast.get_vocab()   )
        self.assertIsInstance(processor_slow.tokenizer				,  lowerCAmelCase   )
        self.assertIsInstance(processor_fast.tokenizer				,  lowerCAmelCase   )

        self.assertEqual(processor_slow.image_processor.to_json_string()				,  image_processor.to_json_string()   )
        self.assertEqual(processor_fast.image_processor.to_json_string()				,  image_processor.to_json_string()   )
        self.assertIsInstance(processor_slow.image_processor				,  lowerCAmelCase   )
        self.assertIsInstance(processor_fast.image_processor				,  lowerCAmelCase   )




  def     A__	(							self   )    ->					str:
        '''simple docstring'''






        _lowercase      			=ChineseCLIPProcessor(tokenizer=self.get_tokenizer()				,  image_processor=self.get_image_processor()   )
        processor.save_pretrained(self.tmpdirname   )

        _lowercase      			=self.get_tokenizer(cls_token='(CLS)'				,  sep_token='(SEP)'   )
        _lowercase      			=self.get_image_processor(do_normalize=lowerCAmelCase   )

        _lowercase      			=ChineseCLIPProcessor.from_pretrained(
            self.tmpdirname				,  cls_token='(CLS)'				,  sep_token='(SEP)'				,  do_normalize=lowerCAmelCase   )

        self.assertEqual(processor.tokenizer.get_vocab()				,  tokenizer_add_kwargs.get_vocab()   )
        self.assertIsInstance(processor.tokenizer				,  lowerCAmelCase   )

        self.assertEqual(processor.image_processor.to_json_string()				,  image_processor_add_kwargs.to_json_string()   )
        self.assertIsInstance(processor.image_processor				,  lowerCAmelCase   )




  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        _lowercase      			=self.get_image_processor()
        _lowercase      			=self.get_tokenizer()

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )

        _lowercase      			=self.prepare_image_inputs()

        _lowercase      			=image_processor(lowerCAmelCase				,  return_tensors='np'   )
        _lowercase      			=processor(images=lowerCAmelCase				,  return_tensors='np'   )

        for key in input_feat_extract.keys():
              self.assertAlmostEqual(input_feat_extract[key].sum()				,  input_processor[key].sum()				,  delta=1e-2   )




  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        _lowercase      			=self.get_image_processor()
        _lowercase      			=self.get_tokenizer()

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )

        _lowercase      			='Alexandra，T-shirt的价格是15便士。'

        _lowercase      			=processor(text=lowerCAmelCase   )

        _lowercase      			=tokenizer(lowerCAmelCase   )

        for key in encoded_tok.keys():
              self.assertListEqual(encoded_tok[key]				,  encoded_processor[key]   )




  def     A__	(							self   )    ->					Dict:
        '''simple docstring'''






        _lowercase      			=self.get_image_processor()
        _lowercase      			=self.get_tokenizer()

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )

        _lowercase      			='Alexandra，T-shirt的价格是15便士。'
        _lowercase      			=self.prepare_image_inputs()

        _lowercase      			=processor(text=lowerCAmelCase				,  images=lowerCAmelCase   )

        self.assertListEqual(list(inputs.keys()   )				,  ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values']   )

        # test if it raises when no input is passed
        with pytest.raises(lowerCAmelCase   ):
              processor()




  def     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        _lowercase      			=self.get_image_processor()
        _lowercase      			=self.get_tokenizer()

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )

        _lowercase      			=[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

        _lowercase      			=processor.batch_decode(lowerCAmelCase   )
        _lowercase      			=tokenizer.batch_decode(lowerCAmelCase   )

        self.assertListEqual(lowerCAmelCase				,  lowerCAmelCase   )




  def     A__	(							self   )    ->					str:
        '''simple docstring'''






        _lowercase      			=self.get_image_processor()
        _lowercase      			=self.get_tokenizer()

        _lowercase      			=ChineseCLIPProcessor(tokenizer=lowerCAmelCase				,  image_processor=lowerCAmelCase   )

        _lowercase      			='Alexandra，T-shirt的价格是15便士。'
        _lowercase      			=self.prepare_image_inputs()

        _lowercase      			=processor(text=lowerCAmelCase				,  images=lowerCAmelCase   )

        self.assertListEqual(list(inputs.keys()   )				,  processor.model_input_names   )


