

"""simple docstring"""






import unittest
from typing import Dict, List, Optional, Union

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 BridgeTowerImageProcessor







class 	__UpperCamelCase    (    unittest.TestCase						):

  def __init__(		self    ,_A    ,_A = True    ,_A = None    ,_A = 32    ,_A = True    ,_A = 1 / 255    ,_A = True    ,_A = True    ,_A = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]    ,_A = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]    ,_A = True    ,_A=7    ,_A=30    ,_A=400    ,_A=3    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    parent
      _lowerCAmelCase       :   List[Any]  =    do_resize
      _lowerCAmelCase       :   Dict  =    size if size is not None else {'shortest_edge': 288}
      _lowerCAmelCase       :   str  =    size_divisor
      _lowerCAmelCase       :   List[str]  =    do_rescale
      _lowerCAmelCase       :   int  =    rescale_factor
      _lowerCAmelCase       :   Dict  =    do_normalize
      _lowerCAmelCase       :   str  =    do_center_crop
      _lowerCAmelCase       :   Optional[int]  =    image_mean
      _lowerCAmelCase       :   Dict  =    image_std
      _lowerCAmelCase       :   int  =    do_pad
      _lowerCAmelCase       :   Union[str, Any]  =    batch_size
      _lowerCAmelCase       :   Tuple  =    num_channels
      _lowerCAmelCase       :   List[str]  =    min_resolution
      _lowerCAmelCase       :   Dict  =    max_resolution

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "size_divisor": self.size_divisor,
      }







  def __lowerCamelCase		(		self    ,_A    ,_A=False      ):
      '''simple docstring'''

      if not batched:
          _lowerCAmelCase       :   Optional[Any]  =    self.size['shortest_edge']
          _lowerCAmelCase       :   Tuple  =    image_inputs[0]
          if isinstance(_A    ,Image.Image      ):
              _lowerCAmelCase,					_lowerCAmelCase       :   Optional[Any]  =    image.size
          else:
              _lowerCAmelCase,					_lowerCAmelCase       :   Union[str, Any]  =    image.shape[1], image.shape[2]
          _lowerCAmelCase       :   Union[str, Any]  =    size / min(_A    ,_A      )
          if h < w:
              _lowerCAmelCase,					_lowerCAmelCase       :   List[str]  =    size, scale * w
          else:
              _lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    scale * h, size

          _lowerCAmelCase       :   Optional[int]  =    int((1333 / 800) * size      )
          if max(_A    ,_A      ) > max_size:
              _lowerCAmelCase       :   Union[str, Any]  =    max_size / max(_A    ,_A      )
              _lowerCAmelCase       :   Optional[Any]  =    newh * scale
              _lowerCAmelCase       :   Any  =    neww * scale

          _lowerCAmelCase,					_lowerCAmelCase       :   Union[str, Any]  =    int(newh + 0.5      ), int(neww + 0.5      )
          _lowerCAmelCase,					_lowerCAmelCase       :   Optional[Any]  =    (
              newh // self.size_divisor * self.size_divisor,
              neww // self.size_divisor * self.size_divisor,
          )

      else:
          _lowerCAmelCase       :   List[Any]  =    []
          for image in image_inputs:
              _lowerCAmelCase,					_lowerCAmelCase       :   int  =    self.get_expected_values([image]      )
              expected_values.append((expected_height, expected_width)      )
          _lowerCAmelCase       :   Union[str, Any]  =    max(_A    ,key=lambda _A      : item[0]      )[0]
          _lowerCAmelCase       :   List[str]  =    max(_A    ,key=lambda _A      : item[1]      )[1]

      return expected_height, expected_width







@require_torch
@require_vision
class 	__UpperCamelCase    (    a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		BridgeTowerImageProcessor if is_vision_available() else None

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    BridgeTowerImageProcessingTester(self      )

  @property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return self.image_processor_tester.prepare_image_processor_dict()

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.image_processing_class(**self.image_processor_dict      )
      self.assertTrue(hasattr(_A    ,'image_mean'      )      )
      self.assertTrue(hasattr(_A    ,'image_std'      )      )
      self.assertTrue(hasattr(_A    ,'do_normalize'      )      )
      self.assertTrue(hasattr(_A    ,'do_resize'      )      )
      self.assertTrue(hasattr(_A    ,'size'      )      )
      self.assertTrue(hasattr(_A    ,'size_divisor'      )      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

      # Test not batched input
      _lowerCAmelCase       :   Optional[Any]  =    image_processing(image_inputs[0]    ,return_tensors='pt'      ).pixel_values

      _lowerCAmelCase,					_lowerCAmelCase       :   List[Any]  =    self.image_processor_tester.get_expected_values(_A      )
      self.assertEqual(
          encoded_images.shape    ,(1, self.image_processor_tester.num_channels, expected_height, expected_width)    ,)

      # Test batched
      _lowerCAmelCase       :   Optional[int]  =    image_processing(_A    ,return_tensors='pt'      ).pixel_values

      _lowerCAmelCase,					_lowerCAmelCase       :   Union[str, Any]  =    self.image_processor_tester.get_expected_values(_A    ,batched=_A      )
      self.assertEqual(
          encoded_images.shape    ,(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )    ,)

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

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

      _lowerCAmelCase,					_lowerCAmelCase       :   Optional[Any]  =    self.image_processor_tester.get_expected_values(_A      )
      self.assertEqual(
          encoded_images.shape    ,(1, self.image_processor_tester.num_channels, expected_height, expected_width)    ,)

      # Test batched
      _lowerCAmelCase       :   str  =    image_processing(_A    ,return_tensors='pt'      ).pixel_values

      _lowerCAmelCase,					_lowerCAmelCase       :   List[Any]  =    self.image_processor_tester.get_expected_values(_A    ,batched=_A      )
      self.assertEqual(
          encoded_images.shape    ,(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )    ,)







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    self.image_processing_class(**self.image_processor_dict      )
      # create random PyTorch tensors
      _lowerCAmelCase       :   Optional[int]  =    prepare_image_inputs(self.image_processor_tester    ,equal_resolution=_A    ,torchify=_A      )
      for image in image_inputs:
          self.assertIsInstance(_A    ,torch.Tensor      )

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

      _lowerCAmelCase,					_lowerCAmelCase       :   int  =    self.image_processor_tester.get_expected_values(_A      )
      self.assertEqual(
          encoded_images.shape    ,(1, self.image_processor_tester.num_channels, expected_height, expected_width)    ,)

      # Test batched
      _lowerCAmelCase       :   List[str]  =    image_processing(_A    ,return_tensors='pt'      ).pixel_values

      _lowerCAmelCase,					_lowerCAmelCase       :   Optional[int]  =    self.image_processor_tester.get_expected_values(_A    ,batched=_A      )
      self.assertEqual(
          encoded_images.shape    ,(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )    ,)








"""simple docstring"""






import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 	__UpperCamelCase    (    a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		LDMTextToImagePipeline
  _UpperCAmelCase          =		TEXT_TO_IMAGE_PARAMS - {
      "negative_prompt",
      "negative_prompt_embeds",
      "cross_attention_kwargs",
      "prompt_embeds",
  }
  _UpperCAmelCase          =		PipelineTesterMixin.required_optional_params - {
      "num_images_per_prompt",
      "callback",
      "callback_steps",
  }
  _UpperCAmelCase          =		TEXT_TO_IMAGE_BATCH_PARAMS
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      torch.manual_seed(0      )
      _lowerCAmelCase       :   Optional[int]  =    UNetaDConditionModel(
          block_out_channels=(32, 64)    ,layers_per_block=2    ,sample_size=32    ,in_channels=4    ,out_channels=4    ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,cross_attention_dim=32    ,)
      _lowerCAmelCase       :   Union[str, Any]  =    DDIMScheduler(
          beta_start=0.0_0_0_8_5    ,beta_end=0.0_1_2    ,beta_schedule='scaled_linear'    ,clip_sample=_A    ,set_alpha_to_one=_A    ,)
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Union[str, Any]  =    AutoencoderKL(
          block_out_channels=(32, 64)    ,in_channels=3    ,out_channels=3    ,down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')    ,up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')    ,latent_channels=4    ,)
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Dict  =    CLIPTextConfig(
          bos_token_id=0    ,eos_token_id=2    ,hidden_size=32    ,intermediate_size=37    ,layer_norm_eps=1E-05    ,num_attention_heads=4    ,num_hidden_layers=5    ,pad_token_id=1    ,vocab_size=1000    ,)
      _lowerCAmelCase       :   Tuple  =    CLIPTextModel(_A      )
      _lowerCAmelCase       :   Any  =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      _lowerCAmelCase       :   List[str]  =    {
          'unet': unet,
          'scheduler': scheduler,
          'vqvae': vae,
          'bert': text_encoder,
          'tokenizer': tokenizer,
      }
      return components

  def __lowerCamelCase		(		self    ,_A    ,_A=0      ):
      '''simple docstring'''

      if str(_A      ).startswith('mps'      ):
          _lowerCAmelCase       :   int  =    torch.manual_seed(_A      )
      else:
          _lowerCAmelCase       :   Optional[Any]  =    torch.Generator(device=_A      ).manual_seed(_A      )
      _lowerCAmelCase       :   List[Any]  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator

      _lowerCAmelCase       :   int  =    self.get_dummy_components()
      _lowerCAmelCase       :   str  =    LDMTextToImagePipeline(**_A      )
      pipe.to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   List[Any]  =    self.get_dummy_inputs(_A      )
      _lowerCAmelCase       :   Any  =    pipe(**_A      ).images
      _lowerCAmelCase       :   Optional[int]  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _lowerCAmelCase       :   Tuple  =    np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]      )

      assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-3







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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self    ,_A    ,_A=torch.floataa    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    torch.manual_seed(_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    np.random.RandomState(_A      ).standard_normal((1, 4, 32, 32)      )
      _lowerCAmelCase       :   Optional[Any]  =    torch.from_numpy(_A      ).to(device=_A    ,dtype=_A      )
      _lowerCAmelCase       :   List[str]  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'      ).to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   Optional[Any]  =    self.get_inputs(_A      )
      _lowerCAmelCase       :   List[Any]  =    pipe(**_A      ).images
      _lowerCAmelCase       :   Dict  =    image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 256, 256, 3)
      _lowerCAmelCase       :   str  =    np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]      )
      _lowerCAmelCase       :   Dict  =    np.abs(expected_slice - image_slice      ).max()
      assert max_diff < 1E-3







@nightly
@require_torch_gpu
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self    ,_A    ,_A=torch.floataa    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    torch.manual_seed(_A      )
      _lowerCAmelCase       :   Optional[int]  =    np.random.RandomState(_A      ).standard_normal((1, 4, 32, 32)      )
      _lowerCAmelCase       :   List[Any]  =    torch.from_numpy(_A      ).to(device=_A    ,dtype=_A      )
      _lowerCAmelCase       :   int  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 50,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'      ).to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   str  =    self.get_inputs(_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    pipe(**_A      ).images[0]

      _lowerCAmelCase       :   int  =    load_numpy(
          'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'      )
      _lowerCAmelCase       :   List[str]  =    np.abs(expected_image - image      ).max()
      assert max_diff < 1E-3





