


"""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 	lowercase__				(					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 		UpperCamelCase_  (							self)  ->  List[str]:
      torch.manual_seed(0)
      _lowerCamelCase	:					Any   =		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	:					List[Any]   =		DDIMScheduler(
          beta_start=0.0_00_85      ,   beta_end=0.0_12      ,   beta_schedule="""scaled_linear"""      ,   clip_sample=SCREAMING_SNAKE_CASE      ,   set_alpha_to_one=SCREAMING_SNAKE_CASE      ,   )
      torch.manual_seed(0)
      _lowerCamelCase	:					int   =		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	:					Tuple   =		CLIPTextConfig(
          bos_token_id=0      ,   eos_token_id=2      ,   hidden_size=32      ,   intermediate_size=37      ,   layer_norm_eps=1e-0_5      ,   num_attention_heads=4      ,   num_hidden_layers=5      ,   pad_token_id=1      ,   vocab_size=1000      ,   )
      _lowerCamelCase	:					str   =		CLIPTextModel(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Tuple   =		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 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=0)  ->  str:
      if str(SCREAMING_SNAKE_CASE).startswith("""mps"""):
         _lowerCamelCase	:					Dict   =		torch.manual_seed(SCREAMING_SNAKE_CASE)
      else:
         _lowerCamelCase	:					Optional[int]   =		torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					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 		UpperCamelCase_  (							self)  ->  List[Any]:
      _lowerCamelCase	:					Optional[int]   =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator

      _lowerCamelCase	:					List[Any]   =		self.get_dummy_components()
      _lowerCamelCase	:					int   =		LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE)
      pipe.to(SCREAMING_SNAKE_CASE)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Dict   =		self.get_dummy_inputs(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					List[Any]   =		pipe(**SCREAMING_SNAKE_CASE).images
      _lowerCamelCase	:					Tuple   =		image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _lowerCamelCase	:					Optional[Any]   =		np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14])

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







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





   def 		UpperCamelCase_  (							self)  ->  str:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=torch.floataa      ,   SCREAMING_SNAKE_CASE=0)  ->  List[Any]:
      _lowerCamelCase	:					Optional[int]   =		torch.manual_seed(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					List[str]   =		np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
      _lowerCamelCase	:					List[Any]   =		torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE      ,   dtype=SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					int   =		{
          """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 		UpperCamelCase_  (							self)  ->  Union[str, Any]:
      _lowerCamelCase	:					Any   =		LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(SCREAMING_SNAKE_CASE)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Dict   =		self.get_inputs(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					List[Any]   =		pipe(**SCREAMING_SNAKE_CASE).images
      _lowerCamelCase	:					Tuple   =		image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 256, 256, 3)
      _lowerCamelCase	:					str   =		np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78])
      _lowerCamelCase	:					Optional[int]   =		np.abs(expected_slice - image_slice).max()
      assert max_diff < 1e-3







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





   def 		UpperCamelCase_  (							self)  ->  Optional[int]:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=torch.floataa      ,   SCREAMING_SNAKE_CASE=0)  ->  int:
      _lowerCamelCase	:					Union[str, Any]   =		torch.manual_seed(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Any   =		np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
      _lowerCamelCase	:					str   =		torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE      ,   dtype=SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Tuple   =		{
          """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 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      _lowerCamelCase	:					Union[str, Any]   =		LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(SCREAMING_SNAKE_CASE)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					str   =		self.get_inputs(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Any   =		pipe(**SCREAMING_SNAKE_CASE).images[0]

      _lowerCamelCase	:					Union[str, Any]   =		load_numpy(
          """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""")
      _lowerCamelCase	:					str   =		np.abs(expected_image - image).max()
      assert max_diff < 1e-3




'''simple docstring'''







import os
import sys
import unittest


__lowerCamelCase									=     os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__lowerCamelCase									=     os.path.join(git_repo_path, '''src''', '''transformers''')

__lowerCamelCase									=     '''
{0} = None
'''

__lowerCamelCase									=     '''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__lowerCamelCase									=     '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''


class        A__   (   unittest.TestCase      ):



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""							)
           self.assertIsNone(UpperCamelCase__							)

           A_						       =   find_backend("""    if not is_tokenizers_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tokenizers"""							)

           A_						       =   find_backend("""    if not is_tensorflow_text_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tensorflow_text"""							)

           A_						       =   find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tensorflow_text"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers_and_vision"""							)



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn("""torch"""		,					UpperCamelCase__							)
           self.assertIn("""tensorflow_text"""		,					UpperCamelCase__							)
           self.assertIn("""sentencepiece_and_tokenizers"""		,					UpperCamelCase__							)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertModel"""		,					objects["""tf"""]							)
           self.assertIn("""FlaxBertModel"""		,					objects["""flax"""]							)
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertTokenizer"""		,					objects["""tensorflow_text"""]							)
           self.assertIn("""convert_slow_tokenizer"""		,					objects["""sentencepiece_and_tokenizers"""]							)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   create_dummy_object("""CONSTANT"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					"""\nCONSTANT = None\n"""							)

           A_						       =   create_dummy_object("""function"""		,					"""'torch'"""							)
           self.assertEqual(
               UpperCamelCase__		,					"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""							)

           A_						       =   """
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
           A_						       =   create_dummy_object("""FakeClass"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					UpperCamelCase__							)







    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   """# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
           A_						       =   create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}							)
           self.assertEqual(dummy_files["""torch"""]		,					UpperCamelCase__							)
