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      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







  lowerCamelCase__   =  LDMTextToImagePipeline
  lowerCamelCase__   =  TEXT_TO_IMAGE_PARAMS - {
      '''negative_prompt''',
      '''negative_prompt_embeds''',
      '''cross_attention_kwargs''',
      '''prompt_embeds''',
  }
  lowerCamelCase__   =  PipelineTesterMixin.required_optional_params - {
      '''num_images_per_prompt''',
      '''callback''',
      '''callback_steps''',
  }
  lowerCamelCase__   =  TEXT_TO_IMAGE_BATCH_PARAMS
  lowerCamelCase__   =  False







  def       __A   (							self       :				Any      )     ->		List[Any]:
        torch.manual_seed(0      )
        SCREAMING_SNAKE_CASE_      =     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     ,   )
        SCREAMING_SNAKE_CASE_      =     DDIMScheduler(
            beta_start=0.0_0085     ,   beta_end=0.012     ,   beta_schedule="scaled_linear"     ,   clip_sample=__magic_name__     ,   set_alpha_to_one=__magic_name__     ,   )
        torch.manual_seed(0      )
        SCREAMING_SNAKE_CASE_      =     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      )
        SCREAMING_SNAKE_CASE_      =     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=1_000     ,   )
        SCREAMING_SNAKE_CASE_      =     CLIPTextModel(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"      )

        SCREAMING_SNAKE_CASE_      =     {
            "unet": unet,
            "scheduler": scheduler,
            "vqvae": vae,
            "bert": text_encoder,
            "tokenizer": tokenizer,
        }
        return components







  def       __A   (							self       :				Dict     ,   __magic_name__       :				Optional[int]     ,   __magic_name__       :				Optional[int]=0      )     ->		Optional[int]:
        if str(__magic_name__      ).startswith("mps"      ):
              SCREAMING_SNAKE_CASE_      =     torch.manual_seed(__magic_name__      )
        else:
              SCREAMING_SNAKE_CASE_      =     torch.Generator(device=__magic_name__      ).manual_seed(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     {
            "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       __A   (							self       :				List[str]      )     ->		List[str]:
        SCREAMING_SNAKE_CASE_      =     "cpu"  # ensure determinism for the device-dependent torch.Generator

        SCREAMING_SNAKE_CASE_      =     self.get_dummy_components()
        SCREAMING_SNAKE_CASE_      =     LDMTextToImagePipeline(**__magic_name__      )
        pipe.to(__magic_name__      )
        pipe.set_progress_bar_config(disable=__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     self.get_dummy_inputs(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     pipe(**__magic_name__      ).images
        SCREAMING_SNAKE_CASE_      =     image[0, -3:, -3:, -1]

        assert image.shape == (1, 16, 16, 3)
        SCREAMING_SNAKE_CASE_      =     np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]      )

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



@slow
@require_torch_gpu
class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				List[str]      )     ->		List[Any]:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







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

        SCREAMING_SNAKE_CASE_      =     self.get_inputs(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     pipe(**__magic_name__      ).images
        SCREAMING_SNAKE_CASE_      =     image[0, -3:, -3:, -1].flatten()

        assert image.shape == (1, 256, 256, 3)
        SCREAMING_SNAKE_CASE_      =     np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]      )
        SCREAMING_SNAKE_CASE_      =     np.abs(expected_slice - image_slice      ).max()
        assert max_diff < 1e-3



@nightly
@require_torch_gpu
class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				List[str]      )     ->		str:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







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

        SCREAMING_SNAKE_CASE_      =     self.get_inputs(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     pipe(**__magic_name__      ).images[0]

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



import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


A   :     Tuple       =				DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A   :     Dict       =				"main"
# Default branch name
A   :     List[str]       =				"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
A   :     Tuple       =				"aaaaaaa"
# This commit does not exist, so we should 404.

A   :     int       =				"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
A   :     Tuple       =				"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"


@contextlib.contextmanager
def    a__       (						):
      print("Welcome!" )
      yield
      print("Bye!" )


@contextlib.contextmanager
def    a__       (						):
      print("Bonjour!" )
      yield
      print("Au revoir!" )


class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				Union[str, Any]      )     ->		Any:
        # If the spec is missing, importlib would not be able to import the module dynamically.
        assert transformers.__spec__ is not None
        assert importlib.util.find_spec("transformers"      ) is not None



class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]      )     ->		Union[str, Any]:
        with ContextManagers([]      ):
              print("Transformers are awesome!"      )
        # The print statement adds a new line at the end of the output
        self.assertEqual(mock_stdout.getvalue()     ,   "Transformers are awesome!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Dict     ,   __magic_name__       :				Union[str, Any]      )     ->		int:
        with ContextManagers([context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Welcome!\nTransformers are awesome!\nBye!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				str      )     ->		Union[str, Any]:
        with ContextManagers([context_fr(), context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English and French welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )







  @require_torch
  def       __A   (							self       :				List[str]      )     ->		Union[str, Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_tf
  def       __A   (							self       :				List[str]      )     ->		Optional[Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_flax
  def       __A   (							self       :				int      )     ->		Tuple:
        # Flax models don't have labels
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


