


import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()


class 			lowerCamelCase_  (     unittest.TestCase				):






    '''simple docstring'''






    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







    @property
    def     UpperCamelCase__     (			self) ->			int:
        __UpperCamelCase  :Dict    						=	1
        __UpperCamelCase  :int    						=	3
        __UpperCamelCase  :Dict    						=	(32, 32)

        __UpperCamelCase  :Any    						=	floats_tensor((batch_size, num_channels) + sizes				,				rng=random.Random(0)).to(__lowercase)
        return image







    @property
    def     UpperCamelCase__     (			self) ->			int:
        torch.manual_seed(0)
        __UpperCamelCase  :List[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				,				)
        return model







    @property
    def     UpperCamelCase__     (			self) ->			Any:
        torch.manual_seed(0)
        __UpperCamelCase  :Union[str, 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				,				)
        return model







    @property
    def     UpperCamelCase__     (			self) ->			int:
        torch.manual_seed(0)
        __UpperCamelCase  :Optional[Any]    						=	RobertaSeriesConfig(
            hidden_size=32				,				project_dim=32				,				intermediate_size=37				,				layer_norm_eps=1E-0_5				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=5_006				,				)
        return RobertaSeriesModelWithTransformation(__lowercase)







    @property
    def     UpperCamelCase__     (			self) ->			Optional[int]:
        def extract(*__lowercase				,				**__lowercase):


            class 			lowerCamelCase_  :






                '''simple docstring'''






                def __init__(			self) ->			Union[str, Any]:
                    __UpperCamelCase  :Any    						=	torch.ones([0])







                def     UpperCamelCase__     (			self				,				__lowercase) ->			List[str]:
                    self.pixel_values.to(__lowercase)
                    return self
            return Out()

        return extract







    def     UpperCamelCase__     (			self) ->			Any:
        __UpperCamelCase  :int    						=	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        __UpperCamelCase  :List[str]    						=	self.dummy_cond_unet
        __UpperCamelCase  :Any    						=	PNDMScheduler(skip_prk_steps=__lowercase)
        __UpperCamelCase  :str    						=	self.dummy_vae
        __UpperCamelCase  :int    						=	self.dummy_text_encoder
        __UpperCamelCase  :Optional[int]    						=	XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''')
        __UpperCamelCase  :List[str]    						=	77

        __UpperCamelCase  :int    						=	self.dummy_image.to(__lowercase)
        __UpperCamelCase  :Optional[int]    						=	init_image / 2 + 0.5

        # make sure here that pndm scheduler skips prk
        __UpperCamelCase  :Any    						=	AltDiffusionImgaImgPipeline(
            unet=__lowercase				,				scheduler=__lowercase				,				vae=__lowercase				,				text_encoder=__lowercase				,				tokenizer=__lowercase				,				safety_checker=__lowercase				,				feature_extractor=self.dummy_extractor				,				)
        __UpperCamelCase  :List[Any]    						=	VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,				do_normalize=__lowercase)
        __UpperCamelCase  :int    						=	alt_pipe.to(__lowercase)
        alt_pipe.set_progress_bar_config(disable=__lowercase)

        __UpperCamelCase  :Optional[Any]    						=	'''A painting of a squirrel eating a burger'''
        __UpperCamelCase  :Any    						=	torch.Generator(device=__lowercase).manual_seed(0)
        __UpperCamelCase  :Dict    						=	alt_pipe(
            [prompt]				,				generator=__lowercase				,				guidance_scale=6.0				,				num_inference_steps=2				,				output_type='''np'''				,				image=__lowercase				,				)

        __UpperCamelCase  :Tuple    						=	output.images

        __UpperCamelCase  :List[Any]    						=	torch.Generator(device=__lowercase).manual_seed(0)
        __UpperCamelCase  :List[Any]    						=	alt_pipe(
            [prompt]				,				generator=__lowercase				,				guidance_scale=6.0				,				num_inference_steps=2				,				output_type='''np'''				,				image=__lowercase				,				return_dict=__lowercase				,				)[0]

        __UpperCamelCase  :Tuple    						=	image[0, -3:, -3:, -1]
        __UpperCamelCase  :List[Any]    						=	image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        __UpperCamelCase  :str    						=	np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99])

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







    @unittest.skipIf(torch_device != '''cuda'''				,				'''This test requires a GPU''')
    def     UpperCamelCase__     (			self) ->			int:
        __UpperCamelCase  :Tuple    						=	self.dummy_cond_unet
        __UpperCamelCase  :Optional[int]    						=	PNDMScheduler(skip_prk_steps=__lowercase)
        __UpperCamelCase  :List[Any]    						=	self.dummy_vae
        __UpperCamelCase  :Tuple    						=	self.dummy_text_encoder
        __UpperCamelCase  :Dict    						=	XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''')
        __UpperCamelCase  :Optional[Any]    						=	77

        __UpperCamelCase  :Tuple    						=	self.dummy_image.to(__lowercase)

        # put models in fp16
        __UpperCamelCase  :Dict    						=	unet.half()
        __UpperCamelCase  :Tuple    						=	vae.half()
        __UpperCamelCase  :Optional[Any]    						=	bert.half()

        # make sure here that pndm scheduler skips prk
        __UpperCamelCase  :List[Any]    						=	AltDiffusionImgaImgPipeline(
            unet=__lowercase				,				scheduler=__lowercase				,				vae=__lowercase				,				text_encoder=__lowercase				,				tokenizer=__lowercase				,				safety_checker=__lowercase				,				feature_extractor=self.dummy_extractor				,				)
        __UpperCamelCase  :Optional[Any]    						=	VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,				do_normalize=__lowercase)
        __UpperCamelCase  :Optional[Any]    						=	alt_pipe.to(__lowercase)
        alt_pipe.set_progress_bar_config(disable=__lowercase)

        __UpperCamelCase  :List[Any]    						=	'''A painting of a squirrel eating a burger'''
        __UpperCamelCase  :str    						=	torch.manual_seed(0)
        __UpperCamelCase  :Dict    						=	alt_pipe(
            [prompt]				,				generator=__lowercase				,				num_inference_steps=2				,				output_type='''np'''				,				image=__lowercase				,				).images

        assert image.shape == (1, 32, 32, 3)







    @unittest.skipIf(torch_device != '''cuda'''				,				'''This test requires a GPU''')
    def     UpperCamelCase__     (			self) ->			str:
        __UpperCamelCase  :Optional[int]    						=	load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/img2img/sketch-mountains-input.jpg''')
        # resize to resolution that is divisible by 8 but not 16 or 32
        __UpperCamelCase  :str    						=	init_image.resize((760, 504))

        __UpperCamelCase  :Optional[Any]    						=	'''BAAI/AltDiffusion'''
        __UpperCamelCase  :Tuple    						=	AltDiffusionImgaImgPipeline.from_pretrained(
            __lowercase				,				safety_checker=__lowercase				,				)
        pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        pipe.enable_attention_slicing()

        __UpperCamelCase  :List[str]    						=	'''A fantasy landscape, trending on artstation'''

        __UpperCamelCase  :List[str]    						=	torch.manual_seed(0)
        __UpperCamelCase  :Optional[int]    						=	pipe(
            prompt=__lowercase				,				image=__lowercase				,				strength=0.75				,				guidance_scale=7.5				,				generator=__lowercase				,				output_type='''np'''				,				)
        __UpperCamelCase  :List[str]    						=	output.images[0]

        __UpperCamelCase  :List[str]    						=	image[255:258, 383:386, -1]

        assert image.shape == (504, 760, 3)
        __UpperCamelCase  :str    						=	np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00])

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


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






    '''simple docstring'''






    def     UpperCamelCase__     (			self) ->			Tuple:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







    def     UpperCamelCase__     (			self) ->			List[str]:
        __UpperCamelCase  :List[Any]    						=	load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/img2img/sketch-mountains-input.jpg''')
        __UpperCamelCase  :List[str]    						=	init_image.resize((768, 512))
        __UpperCamelCase  :List[Any]    						=	load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''')

        __UpperCamelCase  :int    						=	'''BAAI/AltDiffusion'''
        __UpperCamelCase  :List[str]    						=	AltDiffusionImgaImgPipeline.from_pretrained(
            __lowercase				,				safety_checker=__lowercase				,				)
        pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        pipe.enable_attention_slicing()

        __UpperCamelCase  :Tuple    						=	'''A fantasy landscape, trending on artstation'''

        __UpperCamelCase  :Dict    						=	torch.manual_seed(0)
        __UpperCamelCase  :Dict    						=	pipe(
            prompt=__lowercase				,				image=__lowercase				,				strength=0.75				,				guidance_scale=7.5				,				generator=__lowercase				,				output_type='''np'''				,				)
        __UpperCamelCase  :Tuple    						=	output.images[0]

        assert image.shape == (512, 768, 3)
        # img2img is flaky across GPUs even in fp32, so using MAE here
        assert np.abs(expected_image - image).max() < 1E-2






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available


__lowercase											=      {
    '''configuration_audio_spectrogram_transformer''': [
        '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''ASTConfig''',
    ]
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowercase											=      [
        '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
        '''ASTForAudioClassification''',
        '''ASTModel''',
        '''ASTPreTrainedModel''',
    ]

try:
    if not is_speech_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowercase											=      ['''ASTFeatureExtractor''']

if TYPE_CHECKING:
    from .configuration_audio_spectrogram_transformer import (
        AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
        ASTConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_audio_spectrogram_transformer import (
            AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
            ASTForAudioClassification,
            ASTModel,
            ASTPreTrainedModel,
        )

    try:
        if not is_speech_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor


else:
    import sys

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





