
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()







class 					UpperCAmelCase_				(							unittest.TestCase    ):




    @property
    def 						__lowerCamelCase (					self  :   Union[str, Any]   )	-> List[Any]:
      a__     		=     1
      a__     		=     3
      a__     		=     (32, 32)

      a__     		=     floats_tensor((batch_size, num_channels) + sizes      ,      rng=random.Random(0   )   ).to(_A   )
      return image




    @property
    def 						__lowerCamelCase (					self  :   Optional[Any]   )	-> List[str]:
      torch.manual_seed(0   )
      a__     		=     UNetaDModel(
          block_out_channels=(32, 64)      ,      layers_per_block=2      ,      sample_size=32      ,      in_channels=6      ,      out_channels=3      ,      down_block_types=("DownBlock2D", "AttnDownBlock2D")      ,      up_block_types=("AttnUpBlock2D", "UpBlock2D")      ,      )
      return model




    @property
    def 						__lowerCamelCase (					self  :   Any   )	-> Optional[int]:
      torch.manual_seed(0   )
      a__     		=     VQModel(
          block_out_channels=[32, 64]      ,      in_channels=3      ,      out_channels=3      ,      down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]      ,      up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]      ,      latent_channels=3      ,      )
      return model




    def 						__lowerCamelCase (					self  :   Optional[int]   )	-> int:
      a__     		=     'cpu'
      a__     		=     self.dummy_uncond_unet
      a__     		=     DDIMScheduler()
      a__     		=     self.dummy_vq_model

      a__     		=     LDMSuperResolutionPipeline(unet=_A      ,      vqvae=_A      ,      scheduler=_A   )
      ldm.to(_A   )
      ldm.set_progress_bar_config(disable=_A   )

      a__     		=     self.dummy_image.to(_A   )

      a__     		=     torch.Generator(device=_A   ).manual_seed(0   )
      a__     		=     ldm(image=_A      ,      generator=_A      ,      num_inference_steps=2      ,      output_type="numpy"   ).images

      a__     		=     image[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)
      a__     		=     np.array([0.8_678, 0.8_245, 0.6_381, 0.6_830, 0.4_385, 0.5_599, 0.4_641, 0.6_201, 0.5_150]   )

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




    @unittest.skipIf(torch_device != "cuda"      ,      "This test requires a GPU"   )
    def 						__lowerCamelCase (					self  :   List[Any]   )	-> List[Any]:
      a__     		=     self.dummy_uncond_unet
      a__     		=     DDIMScheduler()
      a__     		=     self.dummy_vq_model

      # put models in fp16
      a__     		=     unet.half()
      a__     		=     vqvae.half()

      a__     		=     LDMSuperResolutionPipeline(unet=_A      ,      vqvae=_A      ,      scheduler=_A   )
      ldm.to(_A   )
      ldm.set_progress_bar_config(disable=_A   )

      a__     		=     self.dummy_image.to(_A   )

      a__     		=     ldm(_A      ,      num_inference_steps=2      ,      output_type="numpy"   ).images

      assert image.shape == (1, 64, 64, 3)







@slow
@require_torch
class 					UpperCAmelCase_				(							unittest.TestCase    ):




    def 						__lowerCamelCase (					self  :   str   )	-> Dict:
      a__     		=     load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/vq_diffusion/teddy_bear_pool.png"   )
      a__     		=     init_image.resize((64, 64)      ,      resample=PIL_INTERPOLATION["lanczos"]   )

      a__     		=     LDMSuperResolutionPipeline.from_pretrained("duongna/ldm-super-resolution"      ,      device_map="auto"   )
      ldm.set_progress_bar_config(disable=_A   )

      a__     		=     torch.manual_seed(0   )
      a__     		=     ldm(image=_A      ,      generator=_A      ,      num_inference_steps=20      ,      output_type="numpy"   ).images

      a__     		=     image[0, -3:, -3:, -1]

      assert image.shape == (1, 256, 256, 3)
      a__     		=     np.array([0.7_644, 0.7_679, 0.7_642, 0.7_633, 0.7_666, 0.7_560, 0.7_425, 0.7_257, 0.6_907]   )

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


import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_SCREAMING_SNAKE_CASE   						=    logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE   						=    {
    """facebook/sam-vit-huge""": """https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json""",
    """facebook/sam-vit-large""": """https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json""",
    """facebook/sam-vit-base""": """https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json""",
}







class 					UpperCAmelCase_				(							_a    ):




    def __init__(					self  :   List[str]      ,      lowerCAmelCase  :   str=256      ,      lowerCAmelCase  :   Any=1024      ,      lowerCAmelCase  :   List[str]=16      ,      lowerCAmelCase  :   Union[str, Any]=16      ,      lowerCAmelCase  :   int=4      ,      lowerCAmelCase  :   List[Any]="gelu"      ,      lowerCAmelCase  :   str=1e-6      ,      **lowerCAmelCase  :   Union[str, Any]      ,      )	-> Union[str, Any]:
      super().__init__(**lowerCAmelCase   )
      a__     		=     hidden_size
      a__     		=     image_size
      a__     		=     patch_size
      a__     		=     image_size // patch_size
      a__     		=     mask_input_channels
      a__     		=     num_point_embeddings
      a__     		=     hidden_act
      a__     		=     layer_norm_eps







class 					UpperCAmelCase_				(							_a    ):




    def __init__(					self  :   Dict      ,      lowerCAmelCase  :   str=256      ,      lowerCAmelCase  :   Union[str, Any]="relu"      ,      lowerCAmelCase  :   Optional[int]=2048      ,      lowerCAmelCase  :   Any=2      ,      lowerCAmelCase  :   Any=8      ,      lowerCAmelCase  :   Optional[Any]=2      ,      lowerCAmelCase  :   Optional[Any]=3      ,      lowerCAmelCase  :   Union[str, Any]=3      ,      lowerCAmelCase  :   List[str]=256      ,      lowerCAmelCase  :   Optional[Any]=1e-6      ,      **lowerCAmelCase  :   Any      ,      )	-> int:
      super().__init__(**lowerCAmelCase   )
      a__     		=     hidden_size
      a__     		=     hidden_act
      a__     		=     mlp_dim
      a__     		=     num_hidden_layers
      a__     		=     num_attention_heads
      a__     		=     attention_downsample_rate
      a__     		=     num_multimask_outputs
      a__     		=     iou_head_depth
      a__     		=     iou_head_hidden_dim
      a__     		=     layer_norm_eps







class 					UpperCAmelCase_				(							_a    ):




    def __init__(					self  :   Optional[Any]      ,      lowerCAmelCase  :   Optional[Any]=768      ,      lowerCAmelCase  :   int=256      ,      lowerCAmelCase  :   Tuple=12      ,      lowerCAmelCase  :   List[str]=12      ,      lowerCAmelCase  :   Tuple=3      ,      lowerCAmelCase  :   Any=1024      ,      lowerCAmelCase  :   Dict=16      ,      lowerCAmelCase  :   Dict="gelu"      ,      lowerCAmelCase  :   List[Any]=1e-0_6      ,      lowerCAmelCase  :   Any=0.0      ,      lowerCAmelCase  :   Optional[Any]=1e-1_0      ,      lowerCAmelCase  :   Tuple=True      ,      lowerCAmelCase  :   Tuple=4.0      ,      lowerCAmelCase  :   Optional[Any]=True      ,      lowerCAmelCase  :   List[str]=True      ,      lowerCAmelCase  :   Dict=14      ,      lowerCAmelCase  :   Optional[int]=[2, 5, 8, 11]      ,      lowerCAmelCase  :   List[str]=128      ,      lowerCAmelCase  :   List[str]=None      ,      **lowerCAmelCase  :   str      ,      )	-> Optional[int]:
      super().__init__(**lowerCAmelCase   )

      a__     		=     hidden_size
      a__     		=     output_channels
      a__     		=     num_hidden_layers
      a__     		=     num_attention_heads
      a__     		=     num_channels
      a__     		=     image_size
      a__     		=     patch_size
      a__     		=     hidden_act
      a__     		=     layer_norm_eps
      a__     		=     attention_dropout
      a__     		=     initializer_range
      a__     		=     qkv_bias
      a__     		=     mlp_ratio
      a__     		=     use_abs_pos
      a__     		=     use_rel_pos
      a__     		=     window_size
      a__     		=     global_attn_indexes
      a__     		=     num_pos_feats
      a__     		=     int(hidden_size * mlp_ratio   ) if mlp_dim is None else mlp_dim







class 					UpperCAmelCase_				(							_a    ):
    UpperCAmelCase_			:       Optional[Any]						 =							'sam'
    UpperCAmelCase_			:       List[Any]						 =							True




    def __init__(					self  :   Dict      ,      lowerCAmelCase  :   Any=None      ,      lowerCAmelCase  :   Optional[Any]=None      ,      lowerCAmelCase  :   Optional[Any]=None      ,      lowerCAmelCase  :   str=0.02      ,      **lowerCAmelCase  :   int      ,      )	-> Dict:
      super().__init__(**lowerCAmelCase   )
      a__     		=     vision_config if vision_config is not None else {}
      a__     		=     prompt_encoder_config if prompt_encoder_config is not None else {}
      a__     		=     mask_decoder_config if mask_decoder_config is not None else {}

      if isinstance(lowerCAmelCase      ,      lowerCAmelCase   ):
        a__     		=     vision_config.to_dict()
      if isinstance(lowerCAmelCase      ,      lowerCAmelCase   ):
        a__     		=     prompt_encoder_config.to_dict()
      if isinstance(lowerCAmelCase      ,      lowerCAmelCase   ):
        a__     		=     mask_decoder_config.to_dict()

      a__     		=     SamVisionConfig(**lowerCAmelCase   )
      a__     		=     SamPromptEncoderConfig(**lowerCAmelCase   )
      a__     		=     SamMaskDecoderConfig(**lowerCAmelCase   )
      a__     		=     initializer_range




    def 						__lowerCamelCase (					self  :   Optional[Any]   )	-> Union[str, Any]:
      a__     		=     copy.deepcopy(self.__dict__   )
      a__     		=     self.vision_config.to_dict()
      a__     		=     self.prompt_encoder_config.to_dict()
      a__     		=     self.mask_decoder_config.to_dict()
      a__     		=     self.__class__.model_type
      return output

