



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



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







     def 						_a      (self    ):






           '''simple docstring'''



           torch.manual_seed(0    )
           lowerCamelCase								=		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								=		DDIMScheduler(
               beta_start=0.0_0085				,			beta_end=0.012				,			beta_schedule="scaled_linear"				,			clip_sample=__a				,			set_alpha_to_one=__a				,			)
           torch.manual_seed(0    )
           lowerCamelCase								=		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								=		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=10_00				,			)
           lowerCamelCase								=		CLIPTextModel(__a    )
           lowerCamelCase								=		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"    )

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







     def 						_a      (self				,			__a				,			__a=0    ):






           '''simple docstring'''



           if str(__a    ).startswith("mps"    ):
                 lowerCamelCase								=		torch.manual_seed(__a    )
           else:
                 lowerCamelCase								=		torch.Generator(device=__a    ).manual_seed(__a    )
           lowerCamelCase								=		{
               "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    ):






           '''simple docstring'''



           lowerCamelCase								=		"cpu"  # ensure determinism for the device-dependent torch.Generator

           lowerCamelCase								=		self.get_dummy_components()
           lowerCamelCase								=		LDMTextToImagePipeline(**__a    )
           pipe.to(__a    )
           pipe.set_progress_bar_config(disable=__a    )

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

           assert image.shape == (1, 16, 16, 3)
           lowerCamelCase								=		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    ):






           '''simple docstring'''



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







     def 						_a      (self				,			__a				,			__a=torch.floataa				,			__a=0    ):






           '''simple docstring'''



           lowerCamelCase								=		torch.manual_seed(__a    )
           lowerCamelCase								=		np.random.RandomState(__a    ).standard_normal((1, 4, 32, 32)    )
           lowerCamelCase								=		torch.from_numpy(__a    ).to(device=__a				,			dtype=__a    )
           lowerCamelCase								=		{
               "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    ):






           '''simple docstring'''



           lowerCamelCase								=		LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"    ).to(__a    )
           pipe.set_progress_bar_config(disable=__a    )

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

           assert image.shape == (1, 2_56, 2_56, 3)
           lowerCamelCase								=		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]    )
           lowerCamelCase								=		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    ):






           '''simple docstring'''



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







     def 						_a      (self				,			__a				,			__a=torch.floataa				,			__a=0    ):






           '''simple docstring'''



           lowerCamelCase								=		torch.manual_seed(__a    )
           lowerCamelCase								=		np.random.RandomState(__a    ).standard_normal((1, 4, 32, 32)    )
           lowerCamelCase								=		torch.from_numpy(__a    ).to(device=__a				,			dtype=__a    )
           lowerCamelCase								=		{
               "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    ):






           '''simple docstring'''



           lowerCamelCase								=		LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"    ).to(__a    )
           pipe.set_progress_bar_config(disable=__a    )

           lowerCamelCase								=		self.get_inputs(__a    )
           lowerCamelCase								=		pipe(**__a    ).images[0]

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




import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate

def     __lowercase(	UpperCAmelCase__ ):


      """simple docstring"""



      return x + 2






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



     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 3"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result == 3
           self.assertDictEqual(__a				,			{"x": 3}    )

           lowerCamelCase								=		"x = y"
           lowerCamelCase								=		{"y": 5}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 5, "y": 5}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"y = add_two(x)"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "y": 5}    )

           # Won't work without the tool
           with CaptureStdout() as out:
                 lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result is None
           assert "tried to execute add_two" in out.out







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 3"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result == 3
           self.assertDictEqual(__a				,			{"x": 3}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"test_dict = {'x': x, 'y': add_two(x)}"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           self.assertDictEqual(__a				,			{"x": 3, "y": 5}    )
           self.assertDictEqual(__a				,			{"x": 3, "test_dict": {"x": 3, "y": 5}}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 3\ny = 5"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "y": 5}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"text = f'This is x: {x}.'"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == "This is x: 3."
           self.assertDictEqual(__a				,			{"x": 3, "text": "This is x: 3."}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"if x <= 3:\n    y = 2\nelse:\n    y = 5"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 2
           self.assertDictEqual(__a				,			{"x": 3, "y": 2}    )

           lowerCamelCase								=		{"x": 8}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 8, "y": 5}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"test_list = [x, add_two(x)]"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           self.assertListEqual(__a				,			[3, 5]    )
           self.assertDictEqual(__a				,			{"x": 3, "test_list": [3, 5]}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"y = x"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result == 3
           self.assertDictEqual(__a				,			{"x": 3, "y": 3}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"test_list = [x, add_two(x)]\ntest_list[1]"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "test_list": [3, 5]}    )

           lowerCamelCase								=		"test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "test_dict": {"x": 3, "y": 5}}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 0\nfor i in range(3):\n    x = i"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{"range": range}				,			state=__a    )
           assert result == 2
           self.assertDictEqual(__a				,			{"x": 2, "i": 2}    )