


'''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 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_    ,					unittest.TestCase	):



     """simple docstring"""






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







     def a	( self   ):

            '''simple docstring'''

            torch.manual_seed(0   )
            _lowerCAmelCase    :							Optional[int]   			=       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    :							Optional[int]   			=       DDIMScheduler(
                beta_start=0.0_0085      ,	beta_end=0.012      ,	beta_schedule='scaled_linear'      ,	clip_sample=snake_case__      ,	set_alpha_to_one=snake_case__      ,	)
            torch.manual_seed(0   )
            _lowerCAmelCase    :							Optional[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   )
            _lowerCAmelCase    :							str   			=       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      ,	)
            _lowerCAmelCase    :							Union[str, Any]   			=       CLIPTextModel(snake_case__   )
            _lowerCAmelCase    :							Tuple   			=       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )

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







     def a	( self      ,	snake_case__      ,	snake_case__=0   ):

            '''simple docstring'''

            if str(snake_case__   ).startswith('mps'   ):
                   _lowerCAmelCase    :							List[str]   			=       torch.manual_seed(snake_case__   )
            else:
                   _lowerCAmelCase    :							Any   			=       torch.Generator(device=snake_case__   ).manual_seed(snake_case__   )
            _lowerCAmelCase    :							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 a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       'cpu'  # ensure determinism for the device-dependent torch.Generator

            _lowerCAmelCase    :							Any   			=       self.get_dummy_components()
            _lowerCAmelCase    :							Optional[int]   			=       LDMTextToImagePipeline(**snake_case__   )
            pipe.to(snake_case__   )
            pipe.set_progress_bar_config(disable=snake_case__   )

            _lowerCAmelCase    :							Any   			=       self.get_dummy_inputs(snake_case__   )
            _lowerCAmelCase    :							str   			=       pipe(**snake_case__   ).images
            _lowerCAmelCase    :							str   			=       image[0, -3:, -3:, -1]

            assert image.shape == (1, 16, 16, 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 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

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







     def a	( self      ,	snake_case__      ,	snake_case__=torch.floataa      ,	snake_case__=0   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       torch.manual_seed(snake_case__   )
            _lowerCAmelCase    :							Optional[int]   			=       np.random.RandomState(snake_case__   ).standard_normal((1, 4, 32, 32)   )
            _lowerCAmelCase    :							Dict   			=       torch.from_numpy(snake_case__   ).to(device=snake_case__      ,	dtype=snake_case__   )
            _lowerCAmelCase    :							Optional[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 a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'   ).to(snake_case__   )
            pipe.set_progress_bar_config(disable=snake_case__   )

            _lowerCAmelCase    :							Tuple   			=       self.get_inputs(snake_case__   )
            _lowerCAmelCase    :							Tuple   			=       pipe(**snake_case__   ).images
            _lowerCAmelCase    :							Tuple   			=       image[0, -3:, -3:, -1].flatten()

            assert image.shape == (1, 256, 256, 3)
            _lowerCAmelCase    :							int   			=       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    :							Optional[int]   			=       np.abs(expected_slice - image_slice   ).max()
            assert max_diff < 1E-3
@nightly
@require_torch_gpu
class 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

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







     def a	( self      ,	snake_case__      ,	snake_case__=torch.floataa      ,	snake_case__=0   ):

            '''simple docstring'''

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

            '''simple docstring'''

            _lowerCAmelCase    :							List[Any]   			=       LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'   ).to(snake_case__   )
            pipe.set_progress_bar_config(disable=snake_case__   )

            _lowerCAmelCase    :							Optional[int]   			=       self.get_inputs(snake_case__   )
            _lowerCAmelCase    :							Optional[Any]   			=       pipe(**snake_case__   ).images[0]

            _lowerCAmelCase    :							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





'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


lowerCAmelCase    :     int					=						{
    """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""],
    """processing_trocr""": ["""TrOCRProcessor"""],
}


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCAmelCase    :     Optional[Any]					=						[
           """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """TrOCRForCausalLM""",
           """TrOCRPreTrainedModel""",
       ]


if TYPE_CHECKING:
       from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
       from .processing_trocr import TrOCRProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
       import sys

       lowerCAmelCase    :     Any					=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

