

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 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE    ,    unittest.TestCase							):
  _a		    =						ShapEPipeline
  _a		    =						["""prompt"""]
  _a		    =						["""prompt"""]
  _a		    =						[
      """num_images_per_prompt""",
      """num_inference_steps""",
      """generator""",
      """latents""",
      """guidance_scale""",
      """frame_size""",
      """output_type""",
      """return_dict""",
  ]
  _a		    =						False




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






        return 32




  @property
  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        return 32




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






        return self.time_input_dim * 4




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






        return 8




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






        _lowercase			 =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )
        return tokenizer




  @property
  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        torch.manual_seed(0      )
        _lowercase			 =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-05							,     num_attention_heads=4							,     num_hidden_layers=5							,     pad_token_id=1							,     vocab_size=1_000							,     )
        return CLIPTextModelWithProjection(lowerCAmelCase      )




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






        torch.manual_seed(0      )

        _lowercase			 ={
            '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,
        }

        _lowercase			 =PriorTransformer(**lowerCAmelCase      )
        return model




  @property
  def 						A__  (       self      )						->				int:
        '''simple docstring'''






        torch.manual_seed(0      )

        _lowercase			 ={
            '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,
            ),
        }
        _lowercase			 =ShapERenderer(**lowerCAmelCase      )
        return model




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






        _lowercase			 =self.dummy_prior
        _lowercase			 =self.dummy_text_encoder
        _lowercase			 =self.dummy_tokenizer
        _lowercase			 =self.dummy_renderer

        _lowercase			 =HeunDiscreteScheduler(
            beta_schedule='exp'							,     num_train_timesteps=1_024							,     prediction_type='sample'							,     use_karras_sigmas=lowerCAmelCase							,     clip_sample=lowerCAmelCase							,     clip_sample_range=1.0							,     )
        _lowercase			 ={
            'prior': prior,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'renderer': renderer,
            'scheduler': scheduler,
        }

        return components




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase=0      )						->				List[str]:
        '''simple docstring'''






        if str(lowerCAmelCase      ).startswith('mps'      ):
              _lowercase			 =torch.manual_seed(lowerCAmelCase      )
        else:
              _lowercase			 =torch.Generator(device=lowerCAmelCase      ).manual_seed(lowerCAmelCase      )
        _lowercase			 ={
            'prompt': 'horse',
            'generator': generator,
            'num_inference_steps': 1,
            'frame_size': 32,
            'output_type': 'np',
        }
        return inputs




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






        _lowercase			 ='cpu'

        _lowercase			 =self.get_dummy_components()

        _lowercase			 =self.pipeline_class(**lowerCAmelCase      )
        _lowercase			 =pipe.to(lowerCAmelCase      )

        pipe.set_progress_bar_config(disable=lowerCAmelCase      )

        _lowercase			 =pipe(**self.get_dummy_inputs(lowerCAmelCase      )      )
        _lowercase			 =output.images[0]
        _lowercase			 =image[0, -3:, -3:, -1]

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

        _lowercase			 =np.array(
            [
                0.00039216,
                0.00039216,
                0.00039216,
                0.00039216,
                0.00039216,
                0.00039216,
                0.00039216,
                0.00039216,
                0.00039216,
            ]      )

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




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






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




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






        _lowercase			 =torch_device == 'cpu'
        _lowercase			 =True

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




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






        _lowercase			 =self.get_dummy_components()
        _lowercase			 =self.pipeline_class(**lowerCAmelCase      )
        _lowercase			 =pipe.to(lowerCAmelCase      )
        pipe.set_progress_bar_config(disable=lowerCAmelCase      )

        _lowercase			 =1
        _lowercase			 =2

        _lowercase			 =self.get_dummy_inputs(lowerCAmelCase      )

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

        _lowercase			 =pipe(**lowerCAmelCase							,     num_images_per_prompt=lowerCAmelCase      )[0]

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





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




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






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




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






        _lowercase			 =load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/shap_e/test_shap_e_np_out.npy'      )
        _lowercase			 =ShapEPipeline.from_pretrained('openai/shap-e'      )
        _lowercase			 =pipe.to(lowerCAmelCase      )
        pipe.set_progress_bar_config(disable=lowerCAmelCase      )

        _lowercase			 =torch.Generator(device=lowerCAmelCase      ).manual_seed(0      )

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





import unittest

import numpy as np
from datasets import load_dataset

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 BeitImageProcessor





class 				__lowerCAmelCase  (      unittest.TestCase							):




  def __init__(       self							,     lowerCAmelCase							,     lowerCAmelCase=7							,     lowerCAmelCase=3							,     lowerCAmelCase=18							,     lowerCAmelCase=30							,     lowerCAmelCase=400							,     lowerCAmelCase=True							,     lowerCAmelCase=None							,     lowerCAmelCase=True							,     lowerCAmelCase=None							,     lowerCAmelCase=True							,     lowerCAmelCase=[0.5, 0.5, 0.5]							,     lowerCAmelCase=[0.5, 0.5, 0.5]							,     lowerCAmelCase=False							,     )						->				Tuple:
        '''simple docstring'''






        _lowercase			 =size if size is not None else {'height': 20, 'width': 20}
        _lowercase			 =crop_size if crop_size is not None else {'height': 18, 'width': 18}
        _lowercase			 =parent
        _lowercase			 =batch_size
        _lowercase			 =num_channels
        _lowercase			 =image_size
        _lowercase			 =min_resolution
        _lowercase			 =max_resolution
        _lowercase			 =do_resize
        _lowercase			 =size
        _lowercase			 =do_center_crop
        _lowercase			 =crop_size
        _lowercase			 =do_normalize
        _lowercase			 =image_mean
        _lowercase			 =image_std
        _lowercase			 =do_reduce_labels




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






        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_reduce_labels": self.do_reduce_labels,
        }
def   a   (    )					->   Tuple:





      """simple docstring"""



      _lowercase			 =load_dataset('hf-internal-testing/fixtures_ade20k'   ,     split='test'  )

      _lowercase			 =Image.open(dataset[0]['file']  )
      _lowercase			 =Image.open(dataset[1]['file']  )

      return image, map
def   a   (    )					->   Union[str, Any]:





      """simple docstring"""



      _lowercase			 =load_dataset('hf-internal-testing/fixtures_ade20k'   ,     split='test'  )

      _lowercase			 =Image.open(ds[0]['file']  )
      _lowercase			 =Image.open(ds[1]['file']  )
      _lowercase			 =Image.open(ds[2]['file']  )
      _lowercase			 =Image.open(ds[3]['file']  )

      return [imagea, imagea], [mapa, mapa]







@require_torch
@require_vision
class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE    ,    unittest.TestCase							):
  _a		    =						BeitImageProcessor if is_vision_available() else None




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






        _lowercase			 =BeitImageProcessingTester(self      )




  @property
  def 						A__  (       self      )						->				int:
        '''simple docstring'''






        return self.image_processor_tester.prepare_image_processor_dict()




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






        _lowercase			 =self.image_processing_class(**self.image_processor_dict      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'do_resize'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'size'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'do_center_crop'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'center_crop'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'do_normalize'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'image_mean'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'image_std'      )      )




  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        _lowercase			 =self.image_processing_class.from_dict(self.image_processor_dict      )
        self.assertEqual(image_processor.size							,     {'height': 20, 'width': 20}      )
        self.assertEqual(image_processor.crop_size							,     {'height': 18, 'width': 18}      )
        self.assertEqual(image_processor.do_reduce_labels							,     lowerCAmelCase      )

        _lowercase			 =self.image_processing_class.from_dict(
            self.image_processor_dict							,     size=42							,     crop_size=84							,     reduce_labels=lowerCAmelCase      )
        self.assertEqual(image_processor.size							,     {'height': 42, 'width': 42}      )
        self.assertEqual(image_processor.crop_size							,     {'height': 84, 'width': 84}      )
        self.assertEqual(image_processor.do_reduce_labels							,     lowerCAmelCase      )




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






        pass




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






        _lowercase			 =self.image_processing_class(**self.image_processor_dict      )
        # create random PIL images
        _lowercase			 =prepare_image_inputs(self.image_processor_tester							,     equal_resolution=lowerCAmelCase      )
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase							,     Image.Image      )

        # Test not batched input
        _lowercase			 =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
        _lowercase			 =image_processing(lowerCAmelCase							,     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 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        _lowercase			 =self.image_processing_class(**self.image_processor_dict      )
        # create random numpy tensors
        _lowercase			 =prepare_image_inputs(self.image_processor_tester							,     equal_resolution=lowerCAmelCase							,     numpify=lowerCAmelCase      )
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase							,     np.ndarray      )

        # Test not batched input
        _lowercase			 =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
        _lowercase			 =image_processing(lowerCAmelCase							,     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 						A__  (       self      )						->				Dict:
        '''simple docstring'''






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

        # Test not batched input
        _lowercase			 =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
        _lowercase			 =image_processing(lowerCAmelCase							,     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 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        _lowercase			 =self.image_processing_class(**self.image_processor_dict      )
        # create random PyTorch tensors
        _lowercase			 =prepare_image_inputs(self.image_processor_tester							,     equal_resolution=lowerCAmelCase							,     torchify=lowerCAmelCase      )
        _lowercase			 =[]
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase							,     torch.Tensor      )
              maps.append(torch.zeros(image.shape[-2:]      ).long()      )

        # Test not batched input
        _lowercase			 =image_processing(image_inputs[0]							,     maps[0]							,     return_tensors='pt'      )
        self.assertEqual(
            encoding['pixel_values'].shape							,     (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(
            encoding['labels'].shape							,     (
                1,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(encoding['labels'].dtype							,     torch.long      )
        self.assertTrue(encoding['labels'].min().item() >= 0      )
        self.assertTrue(encoding['labels'].max().item() <= 255      )

        # Test batched
        _lowercase			 =image_processing(lowerCAmelCase							,     lowerCAmelCase							,     return_tensors='pt'      )
        self.assertEqual(
            encoding['pixel_values'].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'],
            )							,     )
        self.assertEqual(
            encoding['labels'].shape							,     (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(encoding['labels'].dtype							,     torch.long      )
        self.assertTrue(encoding['labels'].min().item() >= 0      )
        self.assertTrue(encoding['labels'].max().item() <= 255      )

        # Test not batched input (PIL images)
        _lowercase , _lowercase			 =prepare_semantic_single_inputs()

        _lowercase			 =image_processing(lowerCAmelCase							,     lowerCAmelCase							,     return_tensors='pt'      )
        self.assertEqual(
            encoding['pixel_values'].shape							,     (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(
            encoding['labels'].shape							,     (
                1,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(encoding['labels'].dtype							,     torch.long      )
        self.assertTrue(encoding['labels'].min().item() >= 0      )
        self.assertTrue(encoding['labels'].max().item() <= 255      )

        # Test batched input (PIL images)
        _lowercase , _lowercase			 =prepare_semantic_batch_inputs()

        _lowercase			 =image_processing(lowerCAmelCase							,     lowerCAmelCase							,     return_tensors='pt'      )
        self.assertEqual(
            encoding['pixel_values'].shape							,     (
                2,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(
            encoding['labels'].shape							,     (
                2,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )							,     )
        self.assertEqual(encoding['labels'].dtype							,     torch.long      )
        self.assertTrue(encoding['labels'].min().item() >= 0      )
        self.assertTrue(encoding['labels'].max().item() <= 255      )




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






        _lowercase			 =self.image_processing_class(**self.image_processor_dict      )

        # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
        _lowercase , _lowercase			 =prepare_semantic_single_inputs()
        _lowercase			 =image_processing(lowerCAmelCase							,     lowerCAmelCase							,     return_tensors='pt'      )
        self.assertTrue(encoding['labels'].min().item() >= 0      )
        self.assertTrue(encoding['labels'].max().item() <= 150      )

        _lowercase			 =True
        _lowercase			 =image_processing(lowerCAmelCase							,     lowerCAmelCase							,     return_tensors='pt'      )
        self.assertTrue(encoding['labels'].min().item() >= 0      )
        self.assertTrue(encoding['labels'].max().item() <= 255      )


