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_			(						SCREAMING_SNAKE_CASE	,					unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_     			= ShapEPipeline
 UpperCAmelCase_     			= ['prompt']
 UpperCAmelCase_     			= ['prompt']
 UpperCAmelCase_     			= [
     'num_images_per_prompt',
     'num_inference_steps',
     'generator',
     'latents',
     'guidance_scale',
     'frame_size',
     'output_type',
     'return_dict',
 ]
 UpperCAmelCase_     			= False




 @property
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        return 32




 @property
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        return 32




 @property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        return self.time_input_dim * 4




 @property
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        return 8




 @property
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



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




 @property
 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        torch.manual_seed(0)
        lowerCAmelCase__					     = 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(lowercase__)




 @property
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        torch.manual_seed(0)

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

        lowerCAmelCase__					     = PriorTransformer(**lowercase__)
        return model




 @property
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        torch.manual_seed(0)

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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.dummy_prior
        lowerCAmelCase__					     = self.dummy_text_encoder
        lowerCAmelCase__					     = self.dummy_tokenizer
        lowerCAmelCase__					     = self.dummy_renderer

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

        return components




 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  str      ,   lowercase__ :  Any=0):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = 'cpu'

        lowerCAmelCase__					     = self.get_dummy_components()

        lowerCAmelCase__					     = self.pipeline_class(**lowercase__)
        lowerCAmelCase__					     = pipe.to(lowercase__)

        pipe.set_progress_bar_config(disable=lowercase__)

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

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

        lowerCAmelCase__					     = np.array(
            [
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
            ])

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




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = torch_device == 'cpu'
        lowerCAmelCase__					     = True

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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.get_dummy_components()
        lowerCAmelCase__					     = self.pipeline_class(**lowercase__)
        lowerCAmelCase__					     = pipe.to(lowercase__)
        pipe.set_progress_bar_config(disable=lowercase__)

        lowerCAmelCase__					     = 1
        lowerCAmelCase__					     = 2

        lowerCAmelCase__					     = self.get_dummy_inputs(lowercase__)

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

        lowerCAmelCase__					     = pipe(**lowercase__      ,   num_images_per_prompt=lowercase__)[0]

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






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






 '''simple docstring'''






 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



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

        lowerCAmelCase__					     = torch.Generator(device=lowercase__).manual_seed(0)

        lowerCAmelCase__					     = pipe(
            'a shark'      ,   generator=lowercase__      ,   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(lowercase__      ,   lowercase__)

from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
    import torch

if is_tf_available():
    import tensorflow as tf
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= ['image_processor']
 UpperCAmelCase_     			= 'SamImageProcessor'




 def __init__(      self :  Tuple      ,   lowercase__ :  Dict):







        '''simple docstring'''



        super().__init__(lowercase__)
        lowerCAmelCase__					     = self.image_processor
        lowerCAmelCase__					     = -10
        lowerCAmelCase__					     = self.image_processor.size['longest_edge']




 def __call__(      self :  List[Any]      ,   lowercase__ :  Optional[int]=None      ,   lowercase__ :  Any=None      ,   lowercase__ :  Tuple=None      ,   lowercase__ :  List[str]=None      ,   lowercase__ :  Optional[Union[str, TensorType]] = None      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = self.image_processor(
            lowercase__      ,   return_tensors=lowercase__      ,   **lowercase__      ,   )

        # pop arguments that are not used in the foward but used nevertheless
        lowerCAmelCase__					     = encoding_image_processor['original_sizes']

        if hasattr(lowercase__      ,   'numpy'):  # Checks if Torch or TF tensor
               lowerCAmelCase__					     = original_sizes.numpy()

        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self._check_and_preprocess_points(
            input_points=lowercase__      ,   input_labels=lowercase__      ,   input_boxes=lowercase__      ,   )

        lowerCAmelCase__					     = self._normalize_and_convert(
            lowercase__      ,   lowercase__      ,   input_points=lowercase__      ,   input_labels=lowercase__      ,   input_boxes=lowercase__      ,   return_tensors=lowercase__      ,   )

        return encoding_image_processor




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  List[str]      ,   lowercase__ :  List[str]      ,   lowercase__ :  str=None      ,   lowercase__ :  Optional[int]=None      ,   lowercase__ :  str=None      ,   lowercase__ :  Optional[Any]="pt"      ,   ):







        '''simple docstring'''



        if input_points is not None:
               if len(lowercase__) != len(lowercase__):
                      lowerCAmelCase__					     = [
                          self._normalize_coordinates(self.target_size      ,   lowercase__      ,   original_sizes[0]) for point in input_points
                      ]
               else:
                      lowerCAmelCase__					     = [
                          self._normalize_coordinates(self.target_size      ,   lowercase__      ,   lowercase__)
                          for point, original_size in zip(lowercase__      ,   lowercase__)
                      ]
               # check that all arrays have the same shape
               if not all(point.shape == input_points[0].shape for point in input_points):
                      if input_labels is not None:
                             lowerCAmelCase__     , lowerCAmelCase__					     = self._pad_points_and_labels(lowercase__      ,   lowercase__)

               lowerCAmelCase__					     = np.array(lowercase__)

        if input_labels is not None:
               lowerCAmelCase__					     = np.array(lowercase__)

        if input_boxes is not None:
               if len(lowercase__) != len(lowercase__):
                      lowerCAmelCase__					     = [
                          self._normalize_coordinates(self.target_size      ,   lowercase__      ,   original_sizes[0]      ,   is_bounding_box=lowercase__)
                          for box in input_boxes
                      ]
               else:
                      lowerCAmelCase__					     = [
                          self._normalize_coordinates(self.target_size      ,   lowercase__      ,   lowercase__      ,   is_bounding_box=lowercase__)
                          for box, original_size in zip(lowercase__      ,   lowercase__)
                      ]
               lowerCAmelCase__					     = np.array(lowercase__)

        if input_boxes is not None:
               if return_tensors == "pt":
                      lowerCAmelCase__					     = torch.from_numpy(lowercase__)
                      # boxes batch size of 1 by default
                      lowerCAmelCase__					     = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes
               elif return_tensors == "tf":
                      lowerCAmelCase__					     = tf.convert_to_tensor(lowercase__)
                      # boxes batch size of 1 by default
                      lowerCAmelCase__					     = tf.expand_dims(lowercase__      ,   1) if len(input_boxes.shape) != 3 else input_boxes
               encoding_image_processor.update({'input_boxes': input_boxes})
        if input_points is not None:
               if return_tensors == "pt":
                      lowerCAmelCase__					     = torch.from_numpy(lowercase__)
                      # point batch size of 1 by default
                      lowerCAmelCase__					     = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points
               elif return_tensors == "tf":
                      lowerCAmelCase__					     = tf.convert_to_tensor(lowercase__)
                      # point batch size of 1 by default
                      lowerCAmelCase__					     = tf.expand_dims(lowercase__      ,   1) if len(input_points.shape) != 4 else input_points
               encoding_image_processor.update({'input_points': input_points})
        if input_labels is not None:
               if return_tensors == "pt":
                      lowerCAmelCase__					     = torch.from_numpy(lowercase__)
                      # point batch size of 1 by default
                      lowerCAmelCase__					     = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels
               elif return_tensors == "tf":
                      lowerCAmelCase__					     = tf.convert_to_tensor(lowercase__)
                      # point batch size of 1 by default
                      lowerCAmelCase__					     = tf.expand_dims(lowercase__      ,   1) if len(input_labels.shape) != 3 else input_labels
               encoding_image_processor.update({'input_labels': input_labels})

        return encoding_image_processor




 def 		__snake_case						(      self :  str      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = max([point.shape[0] for point in input_points])
        lowerCAmelCase__					     = []
        for i, point in enumerate(lowercase__):
               if point.shape[0] != expected_nb_points:
                      lowerCAmelCase__					     = np.concatenate(
                          [point, np.zeros((expected_nb_points - point.shape[0], 2)) + self.point_pad_value]      ,   axis=0)
                      lowerCAmelCase__					     = np.append(input_labels[i]      ,   [self.point_pad_value])
               processed_input_points.append(lowercase__)
        lowerCAmelCase__					     = processed_input_points
        return input_points, input_labels




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  int      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  int      ,   lowercase__ :  Optional[Any]=False):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = original_size
        lowerCAmelCase__     , lowerCAmelCase__					     = self.image_processor._get_preprocess_shape(lowercase__      ,   longest_edge=lowercase__)
        lowerCAmelCase__					     = deepcopy(lowercase__).astype(lowercase__)

        if is_bounding_box:
               lowerCAmelCase__					     = coords.reshape(-1      ,   2      ,   2)

        lowerCAmelCase__					     = coords[..., 0] * (new_w / old_w)
        lowerCAmelCase__					     = coords[..., 1] * (new_h / old_h)

        if is_bounding_box:
               lowerCAmelCase__					     = coords.reshape(-1      ,   4)

        return coords




 def 		__snake_case						(      self :  Dict      ,   lowercase__ :  Optional[Any]=None      ,   lowercase__ :  Tuple=None      ,   lowercase__ :  int=None      ,   ):







        '''simple docstring'''



        if input_points is not None:
               if hasattr(lowercase__      ,   'numpy'):  # Checks for TF or Torch tensor
                      lowerCAmelCase__					     = input_points.numpy().tolist()

               if not isinstance(lowercase__      ,   lowercase__) or not isinstance(input_points[0]      ,   lowercase__):
                      raise ValueError('Input points must be a list of list of floating points.')
               lowerCAmelCase__					     = [np.array(lowercase__) for input_point in input_points]
        else:
               lowerCAmelCase__					     = None

        if input_labels is not None:
               if hasattr(lowercase__      ,   'numpy'):
                      lowerCAmelCase__					     = input_labels.numpy().tolist()

               if not isinstance(lowercase__      ,   lowercase__) or not isinstance(input_labels[0]      ,   lowercase__):
                      raise ValueError('Input labels must be a list of list integers.')
               lowerCAmelCase__					     = [np.array(lowercase__) for label in input_labels]
        else:
               lowerCAmelCase__					     = None

        if input_boxes is not None:
               if hasattr(lowercase__      ,   'numpy'):
                      lowerCAmelCase__					     = input_boxes.numpy().tolist()

               if (
                   not isinstance(lowercase__      ,   lowercase__)
                   or not isinstance(input_boxes[0]      ,   lowercase__)
                   or not isinstance(input_boxes[0][0]      ,   lowercase__)
               ):
                      raise ValueError('Input boxes must be a list of list of list of floating points.')
               lowerCAmelCase__					     = [np.array(lowercase__).astype(np.floataa) for box in input_boxes]
        else:
               lowerCAmelCase__					     = None

        return input_points, input_labels, input_boxes




 @property
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.image_processor.model_input_names
        return list(dict.fromkeys(lowercase__))




 def 		__snake_case						(      self :  int      ,   *lowercase__ :  int      ,   **lowercase__ :  int):







        '''simple docstring'''



        return self.image_processor.post_process_masks(*lowercase__      ,   **lowercase__)
