'''simple docstring'''






import gc
import unittest

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

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference




class    a (       lowerCAmelCase__						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					ShapEPipeline
  __lowerCAmelCase				      =					["prompt"]
  __lowerCAmelCase				      =					["prompt"]
  __lowerCAmelCase				      =					[
      "num_images_per_prompt",
      "num_inference_steps",
      "generator",
      "latents",
      "guidance_scale",
      "frame_size",
      "output_type",
      "return_dict",
  ]
  __lowerCAmelCase				      =					False







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return 32







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return 32







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return self.time_input_dim * 4







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return 8







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[int]		= CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""					)
    return tokenizer







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    torch.manual_seed(0					)
    __UpperCAmelCase:					Tuple		= CLIPTextConfig(
        bos_token_id=0   ,    eos_token_id=2   ,    hidden_size=self.text_embedder_hidden_size   ,    projection_dim=self.text_embedder_hidden_size   ,    intermediate_size=37   ,    layer_norm_eps=1e-0_5   ,    num_attention_heads=4   ,    num_hidden_layers=5   ,    pad_token_id=1   ,    vocab_size=1000   ,    )
    return CLIPTextModelWithProjection(_lowerCamelCase					)







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    torch.manual_seed(0					)

    __UpperCAmelCase:					Union[str, Any]		= {
        """num_attention_heads""": 2,
        """attention_head_dim""": 16,
        """embedding_dim""": self.time_input_dim,
        """num_embeddings""": 32,
        """embedding_proj_dim""": self.text_embedder_hidden_size,
        """time_embed_dim""": self.time_embed_dim,
        """num_layers""": 1,
        """clip_embed_dim""": self.time_input_dim * 2,
        """additional_embeddings""": 0,
        """time_embed_act_fn""": """gelu""",
        """norm_in_type""": """layer""",
        """encoder_hid_proj_type""": None,
        """added_emb_type""": None,
    }

    __UpperCAmelCase:					Tuple		= PriorTransformer(**_lowerCamelCase					)
    return model







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    torch.manual_seed(0					)

    __UpperCAmelCase:					Union[str, Any]		= {
        """param_shapes""": (
            (self.renderer_dim, 93),
            (self.renderer_dim, 8),
            (self.renderer_dim, 8),
            (self.renderer_dim, 8),
        ),
        """d_latent""": self.time_input_dim,
        """d_hidden""": self.renderer_dim,
        """n_output""": 12,
        """background""": (
            0.1,
            0.1,
            0.1,
        ),
    }
    __UpperCAmelCase:					Tuple		= ShapERenderer(**_lowerCamelCase					)
    return model







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[int]		= self.dummy_prior
    __UpperCAmelCase:					Union[str, Any]		= self.dummy_text_encoder
    __UpperCAmelCase:					Dict		= self.dummy_tokenizer
    __UpperCAmelCase:					Tuple		= self.dummy_renderer

    __UpperCAmelCase:					List[Any]		= HeunDiscreteScheduler(
        beta_schedule="""exp"""   ,    num_train_timesteps=1024   ,    prediction_type="""sample"""   ,    use_karras_sigmas=_lowerCamelCase   ,    clip_sample=_lowerCamelCase   ,    clip_sample_range=1.0   ,    )
    __UpperCAmelCase:					Tuple		= {
        """prior""": prior,
        """text_encoder""": text_encoder,
        """tokenizer""": tokenizer,
        """renderer""": renderer,
        """scheduler""": scheduler,
    }

    return components







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_=0					):

    '''simple docstring'''







    if str(_lowerCamelCase					).startswith("""mps"""					):
      __UpperCAmelCase:					Tuple		= torch.manual_seed(_lowerCamelCase					)
    else:
      __UpperCAmelCase:					Dict		= torch.Generator(device=_lowerCamelCase					).manual_seed(_lowerCamelCase					)
    __UpperCAmelCase:					Optional[int]		= {
        """prompt""": """horse""",
        """generator""": generator,
        """num_inference_steps""": 1,
        """frame_size""": 32,
        """output_type""": """np""",
    }
    return inputs







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= """cpu"""

    __UpperCAmelCase:					List[Any]		= self.get_dummy_components()

    __UpperCAmelCase:					Dict		= self.pipeline_class(**_lowerCamelCase					)
    __UpperCAmelCase:					Union[str, Any]		= pipe.to(_lowerCamelCase					)

    pipe.set_progress_bar_config(disable=_lowerCamelCase					)

    __UpperCAmelCase:					int		= pipe(**self.get_dummy_inputs(_lowerCamelCase					)					)
    __UpperCAmelCase:					str		= output.images[0]
    __UpperCAmelCase:					Optional[Any]		= image[0, -3:, -3:, -1]

    assert image.shape == (20, 32, 32, 3)

    __UpperCAmelCase:					str		= np.array(
        [
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
            0.0_0_0_3_9_2_1_6,
        ]					)

    assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2







  def    lowercase_  (							self					):

    '''simple docstring'''







    self._test_inference_batch_consistent(batch_sizes=[1, 2]					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Dict		= torch_device == """cpu"""
    __UpperCAmelCase:					str		= True

    self._test_inference_batch_single_identical(
        batch_size=2   ,    test_max_difference=_lowerCamelCase   ,    relax_max_difference=_lowerCamelCase   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.get_dummy_components()
    __UpperCAmelCase:					Optional[int]		= self.pipeline_class(**_lowerCamelCase					)
    __UpperCAmelCase:					Optional[Any]		= pipe.to(_lowerCamelCase					)
    pipe.set_progress_bar_config(disable=_lowerCamelCase					)

    __UpperCAmelCase:					Any		= 1
    __UpperCAmelCase:					List[Any]		= 2

    __UpperCAmelCase:					List[str]		= self.get_dummy_inputs(_lowerCamelCase					)

    for key in inputs.keys():
      if key in self.batch_params:
        __UpperCAmelCase:					Optional[Any]		= batch_size * [inputs[key]]

    __UpperCAmelCase:					List[str]		= pipe(**_lowerCamelCase   ,    num_images_per_prompt=_lowerCamelCase					)[0]

    assert images.shape[0] == batch_size * num_images_per_prompt




@slow
@require_torch_gpu
class    a (       unittest.TestCase				):



  """simple docstring"""







  def    lowercase_  (							self					):

    '''simple docstring'''







    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[int]		= load_numpy(
        """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
        """/shap_e/test_shap_e_np_out.npy"""					)
    __UpperCAmelCase:					Union[str, Any]		= ShapEPipeline.from_pretrained("""openai/shap-e"""					)
    __UpperCAmelCase:					Dict		= pipe.to(_lowerCamelCase					)
    pipe.set_progress_bar_config(disable=_lowerCamelCase					)

    __UpperCAmelCase:					Dict		= torch.Generator(device=_lowerCamelCase					).manual_seed(0					)

    __UpperCAmelCase:					List[Any]		= pipe(
        """a shark"""   ,    generator=_lowerCamelCase   ,    guidance_scale=15.0   ,    num_inference_steps=64   ,    frame_size=64   ,    output_type="""np"""   ,    ).images[0]

    assert images.shape == (20, 64, 64, 3)

    assert_mean_pixel_difference(_lowerCamelCase   ,    _lowerCamelCase					)






'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import PoolFormerImageProcessor




class    a (       unittest.TestCase				):



  """simple docstring"""







  def __init__(							self   ,    snake_case_   ,    snake_case_=7   ,    snake_case_=3   ,    snake_case_=30   ,    snake_case_=400   ,    snake_case_=True   ,    snake_case_=None   ,    snake_case_=0.9   ,    snake_case_=None   ,    snake_case_=True   ,    snake_case_=[0.5, 0.5, 0.5]   ,    snake_case_=[0.5, 0.5, 0.5]   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= size if size is not None else {"""shortest_edge""": 30}
    __UpperCAmelCase:					str		= crop_size if crop_size is not None else {"""height""": 30, """width""": 30}
    __UpperCAmelCase:					Dict		= parent
    __UpperCAmelCase:					Union[str, Any]		= batch_size
    __UpperCAmelCase:					List[Any]		= num_channels
    __UpperCAmelCase:					List[str]		= min_resolution
    __UpperCAmelCase:					List[str]		= max_resolution
    __UpperCAmelCase:					Tuple		= do_resize_and_center_crop
    __UpperCAmelCase:					Union[str, Any]		= size
    __UpperCAmelCase:					str		= crop_pct
    __UpperCAmelCase:					List[Any]		= crop_size
    __UpperCAmelCase:					str		= do_normalize
    __UpperCAmelCase:					Union[str, Any]		= image_mean
    __UpperCAmelCase:					List[str]		= image_std







  def    lowercase_  (							self					):

    '''simple docstring'''







    return {
        "size": self.size,
        "do_resize_and_center_crop": self.do_resize_and_center_crop,
        "crop_pct": self.crop_pct,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
    }




@require_torch
@require_vision
class    a (       __lowerCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					PoolFormerImageProcessor if is_vision_available() else None







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= PoolFormerImageProcessingTester(self					)







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return self.image_processor_tester.prepare_image_processor_dict()







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    self.assertTrue(hasattr(snake_case_   ,    """do_resize_and_center_crop"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """size"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """crop_pct"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """do_normalize"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_mean"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_std"""					)					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.image_processing_class.from_dict(self.image_processor_dict					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 30}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 30, """width""": 30}					)

    __UpperCAmelCase:					Dict		= self.image_processing_class.from_dict(self.image_processor_dict   ,    size=42   ,    crop_size=84					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 42}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 84, """width""": 84}					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PIL images
    __UpperCAmelCase:					Optional[Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    Image.Image					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values

    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Any		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    # create random numpy tensors
    __UpperCAmelCase:					Union[str, Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    numpify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    np.ndarray					)

    # Test not batched input
    __UpperCAmelCase:					Union[str, Any]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					str		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PyTorch tensors
    __UpperCAmelCase:					Dict		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    torchify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    torch.Tensor					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Optional[int]		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )