

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 	A_		(	SCREAMING_SNAKE_CASE      ,							unittest.TestCase    ):
							_UpperCAmelCase   :  Optional[Any]										=				LDMTextToImagePipeline
							_UpperCAmelCase   :  Any										=				TEXT_TO_IMAGE_PARAMS - {
							    '''negative_prompt''',
							    '''negative_prompt_embeds''',
							    '''cross_attention_kwargs''',
							    '''prompt_embeds''',
							}
							_UpperCAmelCase   :  Optional[Any]										=				PipelineTesterMixin.required_optional_params - {
							    '''num_images_per_prompt''',
							    '''callback''',
							    '''callback_steps''',
							}
							_UpperCAmelCase   :  Union[str, Any]										=				TEXT_TO_IMAGE_BATCH_PARAMS
							_UpperCAmelCase   :  Union[str, Any]										=				False
							def    lowerCAmelCase					(		self		:      Dict):
								torch.manual_seed(0)
								__lowerCamelCase    :    Any 	=			UNetaDConditionModel(
								    block_out_channels=(3_2, 6_4)       ,layers_per_block=2       ,sample_size=3_2       ,in_channels=4       ,out_channels=4       ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')       ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')       ,cross_attention_dim=3_2       ,)
								__lowerCamelCase    :    str 	=			DDIMScheduler(
								    beta_start=0.00085       ,beta_end=0.012       ,beta_schedule='scaled_linear'       ,clip_sample=SCREAMING_SNAKE_CASE__       ,set_alpha_to_one=SCREAMING_SNAKE_CASE__       ,)
								torch.manual_seed(0)
								__lowerCamelCase    :    str 	=			AutoencoderKL(
								    block_out_channels=(3_2, 6_4)       ,in_channels=3       ,out_channels=3       ,down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')       ,up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')       ,latent_channels=4       ,)
								torch.manual_seed(0)
								__lowerCamelCase    :    Union[str, Any] 	=			CLIPTextConfig(
								    bos_token_id=0       ,eos_token_id=2       ,hidden_size=3_2       ,intermediate_size=3_7       ,layer_norm_eps=1E-05       ,num_attention_heads=4       ,num_hidden_layers=5       ,pad_token_id=1       ,vocab_size=1_0_0_0       ,)
								__lowerCamelCase    :    Union[str, Any] 	=			CLIPTextModel(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[Any] 	=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

								__lowerCamelCase    :    int 	=			{
								    'unet': unet,
								    'scheduler': scheduler,
								    'vqvae': vae,
								    'bert': text_encoder,
								    'tokenizer': tokenizer,
								}
								return components
							def    lowerCAmelCase					(		self		:      Dict       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]       ,SCREAMING_SNAKE_CASE__		:      int=0):
								if str(SCREAMING_SNAKE_CASE__).startswith('mps'):
									__lowerCamelCase    :    Optional[int] 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								else:
									__lowerCamelCase    :    Tuple 	=			torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[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		:      Optional[int]):
								__lowerCamelCase    :    Union[str, Any] 	=			'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    :    Optional[int] 	=			self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Tuple 	=			image[0, -3:, -3:, -1]

								assert image.shape == (1, 1_6, 1_6, 3)
								__lowerCamelCase    :    Any 	=			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 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      str):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def    lowerCAmelCase					(		self		:      Union[str, Any]       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      List[Any]=torch.floataa       ,SCREAMING_SNAKE_CASE__		:      Any=0):
								__lowerCamelCase    :    Optional[Any] 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			np.random.RandomState(SCREAMING_SNAKE_CASE__).standard_normal((1, 4, 3_2, 3_2))
								__lowerCamelCase    :    Dict 	=			torch.from_numpy(SCREAMING_SNAKE_CASE__).to(device=SCREAMING_SNAKE_CASE__       ,dtype=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Union[str, Any] 	=			{
								    '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		:      str):
								__lowerCamelCase    :    int 	=			LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(SCREAMING_SNAKE_CASE__)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    int 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    str 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Optional[Any] 	=			image[0, -3:, -3:, -1].flatten()

								assert image.shape == (1, 2_5_6, 2_5_6, 3)
								__lowerCamelCase    :    List[str] 	=			np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878])
								__lowerCamelCase    :    Optional[Any] 	=			np.abs(expected_slice - image_slice).max()
								assert max_diff < 1E-3






@nightly
@require_torch_gpu
class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      Optional[int]):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def    lowerCAmelCase					(		self		:      List[Any]       ,SCREAMING_SNAKE_CASE__		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]=torch.floataa       ,SCREAMING_SNAKE_CASE__		:      int=0):
								__lowerCamelCase    :    List[Any] 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			np.random.RandomState(SCREAMING_SNAKE_CASE__).standard_normal((1, 4, 3_2, 3_2))
								__lowerCamelCase    :    Union[str, Any] 	=			torch.from_numpy(SCREAMING_SNAKE_CASE__).to(device=SCREAMING_SNAKE_CASE__       ,dtype=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			{
								    'prompt': 'A painting of a squirrel eating a burger',
								    'latents': latents,
								    'generator': generator,
								    'num_inference_steps': 5_0,
								    'guidance_scale': 6.0,
								    'output_type': 'numpy',
								}
								return inputs


							def    lowerCAmelCase					(		self		:      Any):
								__lowerCamelCase    :    Dict 	=			LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(SCREAMING_SNAKE_CASE__)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Any 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			pipe(**SCREAMING_SNAKE_CASE__).images[0]

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







import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar






class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    List[Any] 	=			logging.get_logger()

								# the current default level is logging.WARNING
								__lowerCamelCase    :    Dict 	=			logging.get_verbosity()

								logging.set_verbosity_error()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								logging.set_verbosity_warning()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								logging.set_verbosity_info()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								logging.set_verbosity_debug()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								# restore to the original level
								logging.set_verbosity(SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      Optional[Any]):
								__lowerCamelCase    :    Optional[int] 	=			logging.get_verbosity()

								__lowerCamelCase    :    str 	=			logging.get_logger('transformers.models.bart.tokenization_bart')
								__lowerCamelCase    :    Tuple 	=			'Testing 1, 2, 3'

								# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
								if level_origin <= logging.WARNING:
									with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
										logger.warning(SCREAMING_SNAKE_CASE__)
									self.assertEqual(cl.out       ,msg + '\n')

								# this is setting the level for all of `transformers.*` loggers
								logging.set_verbosity_error()

								# should not be able to log warnings
								with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
									logger.warning(SCREAMING_SNAKE_CASE__)
								self.assertEqual(cl.out       ,'')

								# should be able to log warnings again
								logging.set_verbosity_warning()
								with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
									logger.warning(SCREAMING_SNAKE_CASE__)
								self.assertEqual(cl.out       ,msg + '\n')

								# restore to the original level
								logging.set_verbosity(SCREAMING_SNAKE_CASE__)
							@mockenv(TRANSFORMERS_VERBOSITY='error')
							def    lowerCAmelCase					(		self		:      Tuple):
								# reset for the env var to take effect, next time some logger call is made
								transformers.utils.logging._reset_library_root_logger()
								# this action activates the env var
								__lowerCamelCase    :    int 	=			logging.get_logger('transformers.models.bart.tokenization_bart')

								__lowerCamelCase    :    int 	=			os.getenv('TRANSFORMERS_VERBOSITY'       ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			logging.log_levels[env_level_str]

								__lowerCamelCase    :    Tuple 	=			logging.get_verbosity()
								self.assertEqual(
								    SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__       ,F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}"       ,)

								# restore to the original level
								__lowerCamelCase    :    List[str] 	=			''
								transformers.utils.logging._reset_library_root_logger()
							@mockenv(TRANSFORMERS_VERBOSITY='super-error')
							def    lowerCAmelCase					(		self		:      List[Any]):
								# reset for the env var to take effect, next time some logger call is made
								transformers.utils.logging._reset_library_root_logger()
								__lowerCamelCase    :    List[str] 	=			logging.logging.getLogger()
								with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
									# this action activates the env var
									logging.get_logger('transformers.models.bart.tokenization_bart')
								self.assertIn('Unknown option TRANSFORMERS_VERBOSITY=super-error'       ,cl.out)

								# no need to restore as nothing was changed


							def    lowerCAmelCase					(		self		:      Any):
								# testing `logger.warning_advice()`
								transformers.utils.logging._reset_library_root_logger()

								__lowerCamelCase    :    Tuple 	=			logging.get_logger('transformers.models.bart.tokenization_bart')
								__lowerCamelCase    :    Optional[int] 	=			'Testing 1, 2, 3'

								with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='1'):
									# nothing should be logged as env var disables this method
									with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
										logger.warning_advice(SCREAMING_SNAKE_CASE__)
									self.assertEqual(cl.out       ,'')

								with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''):
									# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
									with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
										logger.warning_advice(SCREAMING_SNAKE_CASE__)
									self.assertEqual(cl.out       ,msg + '\n')






def        SCREAMING_SNAKE_CASE__	(  )  ->					Any:
	disable_progress_bar()
	assert are_progress_bars_disabled()

	enable_progress_bar()
	assert not are_progress_bars_disabled()




