


import gc
import inspect
import unittest

import torch
from parameterized import parameterized

from diffusers import PriorTransformer
from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin


enable_full_determinism()


class     lowercase__  (					__SCREAMING_SNAKE_CASE					,							unittest.TestCase		):
  A__=  PriorTransformer
  A__=  'hidden_states'






  @property
  def 			_UpperCAmelCase  (					self      :					Dict ):




         """simple docstring"""







         UpperCAmelCase__										=     4
         UpperCAmelCase__										=     8
         UpperCAmelCase__										=     7

         UpperCAmelCase__										=     floats_tensor((batch_size, embedding_dim) ).to(_lowercase )

         UpperCAmelCase__										=     floats_tensor((batch_size, embedding_dim) ).to(_lowercase )
         UpperCAmelCase__										=     floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(_lowercase )

         return {
             "hidden_states": hidden_states,
             "timestep": 2,
             "proj_embedding": proj_embedding,
             "encoder_hidden_states": encoder_hidden_states,
         }






  def 			_UpperCAmelCase  (					self      :					Union[str, Any]		,						_lowercase      :					List[Any]=0 ):




         """simple docstring"""







         torch.manual_seed(_lowercase )
         UpperCAmelCase__										=     4
         UpperCAmelCase__										=     8
         UpperCAmelCase__										=     7

         UpperCAmelCase__										=     torch.randn((batch_size, embedding_dim) ).to(_lowercase )

         UpperCAmelCase__										=     torch.randn((batch_size, embedding_dim) ).to(_lowercase )
         UpperCAmelCase__										=     torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_lowercase )

         return {
             "hidden_states": hidden_states,
             "timestep": 2,
             "proj_embedding": proj_embedding,
             "encoder_hidden_states": encoder_hidden_states,
         }






  @property
  def 			_UpperCAmelCase  (					self      :					str ):




         """simple docstring"""







         return (4, 8)






  @property
  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         return (4, 8)






  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         UpperCAmelCase__										=     {
             "num_attention_heads": 2,
             "attention_head_dim": 4,
             "num_layers": 2,
             "embedding_dim": 8,
             "num_embeddings": 7,
             "additional_embeddings": 4,
         }
         UpperCAmelCase__										=     self.dummy_input
         return init_dict, inputs_dict






  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         UpperCAmelCase__						,			UpperCAmelCase__										=     PriorTransformer.from_pretrained(
             "hf-internal-testing/prior-dummy"		,						output_loading_info=_lowercase )
         self.assertIsNotNone(_lowercase )
         self.assertEqual(len(loading_info["missing_keys"] )		,						0 )

         model.to(_lowercase )
         UpperCAmelCase__										=     model(**self.dummy_input )[0]

         assert hidden_states is not None, "Make sure output is not None"






  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         UpperCAmelCase__						,			UpperCAmelCase__										=     self.prepare_init_args_and_inputs_for_common()

         UpperCAmelCase__										=     self.model_class(**_lowercase )
         UpperCAmelCase__										=     inspect.signature(model.forward )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         UpperCAmelCase__										=     [*signature.parameters.keys()]

         UpperCAmelCase__										=     ["hidden_states", "timestep"]
         self.assertListEqual(arg_names[:2]		,						_lowercase )






  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy" )
         UpperCAmelCase__										=     model.to(_lowercase )

         if hasattr(_lowercase		,						"set_default_attn_processor" ):
                model.set_default_attn_processor()

         UpperCAmelCase__										=     self.get_dummy_seed_input()

         with torch.no_grad():
                UpperCAmelCase__										=     model(**_lowercase )[0]

         UpperCAmelCase__										=     output[0, :5].flatten().cpu()
         print(_lowercase )

         # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
         # the expected output slices are not the same for CPU and GPU.
         UpperCAmelCase__										=     torch.tensor([-1.3_4_3_6, -0.2_8_7_0, 0.7_5_3_8, 0.4_3_6_8, -0.0_2_3_9] )
         self.assertTrue(torch_all_close(_lowercase		,						_lowercase		,						rtol=1E-2 ) )




@slow
class     lowercase__  (					unittest.TestCase		):






  def 			_UpperCAmelCase  (					self      :					List[Any]		,						_lowercase      :					Optional[Any]=1		,						_lowercase      :					List[Any]=7_68		,						_lowercase      :					Dict=77		,						_lowercase      :					Dict=0 ):




         """simple docstring"""







         torch.manual_seed(_lowercase )
         UpperCAmelCase__										=     batch_size
         UpperCAmelCase__										=     embedding_dim
         UpperCAmelCase__										=     num_embeddings

         UpperCAmelCase__										=     torch.randn((batch_size, embedding_dim) ).to(_lowercase )

         UpperCAmelCase__										=     torch.randn((batch_size, embedding_dim) ).to(_lowercase )
         UpperCAmelCase__										=     torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_lowercase )

         return {
             "hidden_states": hidden_states,
             "timestep": 2,
             "proj_embedding": proj_embedding,
             "encoder_hidden_states": encoder_hidden_states,
         }






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







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






  @parameterized.expand(
      [
          # fmt: off
          [13, [-0.5_8_6_1,  0.1_2_8_3, -0.0_9_3_1,  0.0_8_8_2,  0.4_4_7_6,  0.1_3_2_9, -0.0_4_9_8,  0.0_6_4_0]],
          [37, [-0.4_9_1_3,  0.0_1_1_0, -0.0_4_8_3,  0.0_5_4_1,  0.4_9_5_4, -0.0_1_7_0,  0.0_3_5_4,  0.1_6_5_1]],
          # fmt: on
      ] )
  def 			_UpperCAmelCase  (					self      :					List[Any]		,						_lowercase      :					Any		,						_lowercase      :					List[str] ):




         """simple docstring"""







         UpperCAmelCase__										=     PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior"		,						subfolder="prior" )
         model.to(_lowercase )
         UpperCAmelCase__										=     self.get_dummy_seed_input(seed=_lowercase )

         with torch.no_grad():
                UpperCAmelCase__										=     model(**_lowercase )[0]

         assert list(sample.shape ) == [1, 7_68]

         UpperCAmelCase__										=     sample[0, :8].flatten().cpu()
         print(_lowercase )
         UpperCAmelCase__										=     torch.tensor(_lowercase )

         assert torch_all_close(_lowercase		,						_lowercase		,						atol=1E-3 )









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     lowercase__  (					__SCREAMING_SNAKE_CASE		):
  A__=  ['image_processor']
  A__=  'SamImageProcessor'






  def __init__(					self      :					int		,						_lowercase      :					List[Any] ):




         """simple docstring"""







         super().__init__(_lowercase )
         UpperCAmelCase__										=     self.image_processor
         UpperCAmelCase__										=     -10
         UpperCAmelCase__										=     self.image_processor.size["longest_edge"]






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




         """simple docstring"""







         UpperCAmelCase__										=     self.image_processor(
             _lowercase		,						return_tensors=_lowercase		,						**_lowercase		,						)

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

         if hasattr(_lowercase		,						"numpy" ):  # Checks if Torch or TF tensor
                UpperCAmelCase__										=     original_sizes.numpy()

         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     self._check_and_preprocess_points(
             input_points=_lowercase		,						input_labels=_lowercase		,						input_boxes=_lowercase		,						)

         UpperCAmelCase__										=     self._normalize_and_convert(
             _lowercase		,						_lowercase		,						input_points=_lowercase		,						input_labels=_lowercase		,						input_boxes=_lowercase		,						return_tensors=_lowercase		,						)

         return encoding_image_processor






  def 			_UpperCAmelCase  (					self      :					Dict		,						_lowercase      :					int		,						_lowercase      :					Dict		,						_lowercase      :					Optional[Any]=None		,						_lowercase      :					Any=None		,						_lowercase      :					Union[str, Any]=None		,						_lowercase      :					List[Any]="pt"		,						):




         """simple docstring"""







         if input_points is not None:
                if len(_lowercase ) != len(_lowercase ):
                       UpperCAmelCase__										=     [
                           self._normalize_coordinates(self.target_size		,						_lowercase		,						original_sizes[0] ) for point in input_points
                       ]
                else:
                       UpperCAmelCase__										=     [
                           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:
                              UpperCAmelCase__						,			UpperCAmelCase__										=     self._pad_points_and_labels(_lowercase		,						_lowercase )

                UpperCAmelCase__										=     np.array(_lowercase )

         if input_labels is not None:
                UpperCAmelCase__										=     np.array(_lowercase )

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

         if input_boxes is not None:
                if return_tensors == "pt":
                       UpperCAmelCase__										=     torch.from_numpy(_lowercase )
                       # boxes batch size of 1 by default
                       UpperCAmelCase__										=     input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes
                elif return_tensors == "tf":
                       UpperCAmelCase__										=     tf.convert_to_tensor(_lowercase )
                       # boxes batch size of 1 by default
                       UpperCAmelCase__										=     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":
                       UpperCAmelCase__										=     torch.from_numpy(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points
                elif return_tensors == "tf":
                       UpperCAmelCase__										=     tf.convert_to_tensor(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     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":
                       UpperCAmelCase__										=     torch.from_numpy(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels
                elif return_tensors == "tf":
                       UpperCAmelCase__										=     tf.convert_to_tensor(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     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 			_UpperCAmelCase  (					self      :					Union[str, Any]		,						_lowercase      :					Any		,						_lowercase      :					Optional[Any] ):




         """simple docstring"""







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






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




         """simple docstring"""







         UpperCAmelCase__						,			UpperCAmelCase__										=     original_size
         UpperCAmelCase__						,			UpperCAmelCase__										=     self.image_processor._get_preprocess_shape(_lowercase		,						longest_edge=_lowercase )
         UpperCAmelCase__										=     deepcopy(_lowercase ).astype(_lowercase )

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

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

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

         return coords






  def 			_UpperCAmelCase  (					self      :					int		,						_lowercase      :					Tuple=None		,						_lowercase      :					Optional[Any]=None		,						_lowercase      :					List[Any]=None		,						):




         """simple docstring"""







         if input_points is not None:
                if hasattr(_lowercase		,						"numpy" ):  # Checks for TF or Torch tensor
                       UpperCAmelCase__										=     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." )
                UpperCAmelCase__										=     [np.array(_lowercase ) for input_point in input_points]
         else:
                UpperCAmelCase__										=     None

         if input_labels is not None:
                if hasattr(_lowercase		,						"numpy" ):
                       UpperCAmelCase__										=     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." )
                UpperCAmelCase__										=     [np.array(_lowercase ) for label in input_labels]
         else:
                UpperCAmelCase__										=     None

         if input_boxes is not None:
                if hasattr(_lowercase		,						"numpy" ):
                       UpperCAmelCase__										=     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." )
                UpperCAmelCase__										=     [np.array(_lowercase ).astype(np.floataa ) for box in input_boxes]
         else:
                UpperCAmelCase__										=     None

         return input_points, input_labels, input_boxes






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




         """simple docstring"""







         UpperCAmelCase__										=     self.image_processor.model_input_names
         return list(dict.fromkeys(_lowercase ) )






  def 			_UpperCAmelCase  (					self      :					int		,						*_lowercase      :					List[str]		,						**_lowercase      :					Any ):




         """simple docstring"""







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





