


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_ (       _a			,unittest.TestCase):
						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  _snake_case					(	self						:   Union[str, Any]						)      ->Dict:






									"""simple docstring"""






									torch.manual_seed(0						)
									a__ :Union[str, 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   ,     )
									a__ :Tuple						  =    DDIMScheduler(
									    beta_start=0.00_085   ,     beta_end=0.012   ,     beta_schedule="scaled_linear"   ,     clip_sample=__A   ,     set_alpha_to_one=__A   ,     )
									torch.manual_seed(0						)
									a__ :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						)
									a__ :Optional[int]						  =    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   ,     )
									a__ :Tuple						  =    CLIPTextModel(__A						)
									a__ :Optional[int]						  =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

									a__ :Union[str, Any]						  =    {
									    "unet": unet,
									    "scheduler": scheduler,
									    "vqvae": vae,
									    "bert": text_encoder,
									    "tokenizer": tokenizer,
									}
									return components




						def  _snake_case					(	self						:   Dict   ,     __A						:   Optional[int]   ,     __A						:   str=0						)      ->List[str]:






									"""simple docstring"""






									if str(__A						).startswith("mps"						):
												a__ :int						  =    torch.manual_seed(__A						)
									else:
												a__ :Any						  =    torch.Generator(device=__A						).manual_seed(__A						)
									a__ :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  _snake_case					(	self						:   List[str]						)      ->int:






									"""simple docstring"""






									a__ :Tuple						  =    "cpu"  # ensure determinism for the device-dependent torch.Generator

									a__ :Optional[Any]						  =    self.get_dummy_components()
									a__ :List[str]						  =    LDMTextToImagePipeline(**__A						)
									pipe.to(__A						)
									pipe.set_progress_bar_config(disable=__A						)

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

									assert image.shape == (1, 16, 16, 3)
									a__ :str						  =    np.array([0.6_101, 0.6_156, 0.5_622, 0.4_895, 0.6_661, 0.3_804, 0.5_748, 0.6_136, 0.5_014]						)

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






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




						def  _snake_case					(	self						:   Optional[Any]						)      ->List[str]:






									"""simple docstring"""






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




						def  _snake_case					(	self						:   str   ,     __A						:   Any   ,     __A						:   Any=torch.floataa   ,     __A						:   Optional[int]=0						)      ->Any:






									"""simple docstring"""






									a__ :List[str]						  =    torch.manual_seed(__A						)
									a__ :Optional[Any]						  =    np.random.RandomState(__A						).standard_normal((1, 4, 32, 32)						)
									a__ :str						  =    torch.from_numpy(__A						).to(device=__A   ,     dtype=__A						)
									a__ :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  _snake_case					(	self						:   int						)      ->List[Any]:






									"""simple docstring"""






									a__ :str						  =    LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"						).to(__A						)
									pipe.set_progress_bar_config(disable=__A						)

									a__ :List[Any]						  =    self.get_inputs(__A						)
									a__ :str						  =    pipe(**__A						).images
									a__ :Union[str, Any]						  =    image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 256, 256, 3)
									a__ :str						  =    np.array([0.51_825, 0.52_850, 0.52_543, 0.54_258, 0.52_304, 0.52_569, 0.54_363, 0.55_276, 0.56_878]						)
									a__ :Optional[Any]						  =    np.abs(expected_slice - image_slice						).max()
									assert max_diff < 1E-3






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




						def  _snake_case					(	self						:   List[Any]						)      ->Dict:






									"""simple docstring"""






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




						def  _snake_case					(	self						:   Optional[int]   ,     __A						:   Union[str, Any]   ,     __A						:   int=torch.floataa   ,     __A						:   Any=0						)      ->Optional[Any]:






									"""simple docstring"""






									a__ :Optional[Any]						  =    torch.manual_seed(__A						)
									a__ :Union[str, Any]						  =    np.random.RandomState(__A						).standard_normal((1, 4, 32, 32)						)
									a__ :List[Any]						  =    torch.from_numpy(__A						).to(device=__A   ,     dtype=__A						)
									a__ :Optional[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  _snake_case					(	self						:   Optional[int]						)      ->int:






									"""simple docstring"""






									a__ :Dict						  =    LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"						).to(__A						)
									pipe.set_progress_bar_config(disable=__A						)

									a__ :str						  =    self.get_inputs(__A						)
									a__ :int						  =    pipe(**__A						).images[0]

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






# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


snake_case__			 =						{
    '''configuration_mgp_str''': ['''MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MgpstrConfig'''],
    '''processing_mgp_str''': ['''MgpstrProcessor'''],
    '''tokenization_mgp_str''': ['''MgpstrTokenizer'''],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		snake_case__			 =						[
		    '''MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''MgpstrModel''',
		    '''MgpstrPreTrainedModel''',
		    '''MgpstrForSceneTextRecognition''',
		]

if TYPE_CHECKING:
		from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
		from .processing_mgp_str import MgpstrProcessor
		from .tokenization_mgp_str import MgpstrTokenizer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_mgp_str import (
				    MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
				    MgpstrForSceneTextRecognition,
				    MgpstrModel,
				    MgpstrPreTrainedModel,
				)
else:
		import sys

		snake_case__			 =						_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


