
import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


lowercase_ 				=			logging.get_logger(__name__)





class     __UpperCamelCase (							lowerCAmelCase__       ):






     """simple docstring"""







     lowerCAmelCase_							   =			['''input_values''', '''attention_mask''']



     def __init__(				self							:							Tuple     ,						_A							:							int = 1     ,						_A							:							int = 1_6000     ,						_A							:							float = 0.0     ,						_A							:							bool = False     ,						_A							:							int = 80     ,						_A							:							int = 16     ,						_A							:							int = 64     ,						_A							:							str = "hann_window"     ,						_A							:							float = 1.0     ,						_A							:							float = 80     ,						_A							:							float = 7600     ,						_A							:							float = 1e-10     ,						_A							:							int = 2     ,						_A							:							bool = True     ,						**_A							:							Optional[Any]     ,						):







       """simple docstring"""




       super().__init__(feature_size=_A     ,						sampling_rate=_A     ,						padding_value=_A     ,						**_A )
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		do_normalize
       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		return_attention_mask

       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		num_mel_bins
       __SCREAMING_SNAKE_CASE      :	Dict					=		hop_length
       __SCREAMING_SNAKE_CASE      :	Any					=		win_length
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		win_function
       __SCREAMING_SNAKE_CASE      :	str					=		frame_signal_scale
       __SCREAMING_SNAKE_CASE      :	Tuple					=		fmin
       __SCREAMING_SNAKE_CASE      :	Any					=		fmax
       __SCREAMING_SNAKE_CASE      :	Dict					=		mel_floor
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		reduction_factor

       __SCREAMING_SNAKE_CASE      :	List[str]					=		win_length * sampling_rate // 1000
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		hop_length * sampling_rate // 1000
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		optimal_fft_length(self.sample_size )
       __SCREAMING_SNAKE_CASE      :	str					=		(self.n_fft // 2) + 1

       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		window_function(window_length=self.sample_size     ,						name=self.win_function     ,						periodic=_A )

       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		mel_filter_bank(
           num_frequency_bins=self.n_freqs     ,						num_mel_filters=self.num_mel_bins     ,						min_frequency=self.fmin     ,						max_frequency=self.fmax     ,						sampling_rate=self.sampling_rate     ,						norm='''slaney'''     ,						mel_scale='''slaney'''     ,						)

       if frame_signal_scale != 1.0:
         warnings.warn(
             '''The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers'''     ,						_A     ,						)
       if reduction_factor != 2.0:
         warnings.warn(
             '''The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers'''     ,						_A     ,						)



     @staticmethod
     # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
     def  UpperCAmelCase__							(				_A							:							List[np.ndarray]     ,						_A							:							List[np.ndarray]     ,						_A							:							float = 0.0 ):







       """simple docstring"""




       if attention_mask is not None:
         __SCREAMING_SNAKE_CASE      :	Optional[int]					=		np.array(_A     ,						np.intaa )
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		[]

         for vector, length in zip(_A     ,						attention_mask.sum(-1 ) ):
           __SCREAMING_SNAKE_CASE      :	Tuple					=		(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 )
           if length < normed_slice.shape[0]:
             __SCREAMING_SNAKE_CASE      :	Any					=		padding_value

           normed_input_values.append(_A )
       else:
         __SCREAMING_SNAKE_CASE      :	int					=		[(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values]

       return normed_input_values



     def  UpperCAmelCase__							(				self							:							Any     ,						_A							:							np.ndarray     ,						):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	str					=		spectrogram(
           _A     ,						window=self.window     ,						frame_length=self.sample_size     ,						hop_length=self.sample_stride     ,						fft_length=self.n_fft     ,						mel_filters=self.mel_filters     ,						mel_floor=self.mel_floor     ,						log_mel='''log10'''     ,						)
       return log_mel_spec.T



     def __call__(				self							:							Dict     ,						_A							:							Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None     ,						_A							:							Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None     ,						_A							:							Union[bool, str, PaddingStrategy] = False     ,						_A							:							Optional[int] = None     ,						_A							:							bool = False     ,						_A							:							Optional[int] = None     ,						_A							:							Optional[bool] = None     ,						_A							:							Optional[Union[str, TensorType]] = None     ,						_A							:							Optional[int] = None     ,						**_A							:							str     ,						):







       """simple docstring"""




       if audio is None and audio_target is None:
         raise ValueError('''You must provide either `audio` or `audio_target` values.''' )

       if sampling_rate is not None:
         if sampling_rate != self.sampling_rate:
           raise ValueError(
               F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
               F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'''
               F''' {self.sampling_rate} and not {sampling_rate}.''' )
       else:
         logger.warning(
             '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. '''
             '''Failing to do so can result in silent errors that might be hard to debug.''' )

       if audio is not None:
         __SCREAMING_SNAKE_CASE      :	str					=		self._process_audio(
             _A     ,						_A     ,						_A     ,						_A     ,						_A     ,						_A     ,						_A     ,						_A     ,						**_A     ,						)
       else:
         __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		None

       if audio_target is not None:
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		self._process_audio(
             _A     ,						_A     ,						_A     ,						_A     ,						_A     ,						_A     ,						_A     ,						_A     ,						**_A     ,						)

         if inputs is None:
           return inputs_target
         else:
           __SCREAMING_SNAKE_CASE      :	str					=		inputs_target['''input_values''']
           __SCREAMING_SNAKE_CASE      :	Dict					=		inputs_target.get('''attention_mask''' )
           if decoder_attention_mask is not None:
             __SCREAMING_SNAKE_CASE      :	Tuple					=		decoder_attention_mask

       return inputs



     def  UpperCAmelCase__							(				self							:							Tuple     ,						_A							:							Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]     ,						_A							:							bool = False     ,						_A							:							Union[bool, str, PaddingStrategy] = False     ,						_A							:							Optional[int] = None     ,						_A							:							bool = False     ,						_A							:							Optional[int] = None     ,						_A							:							Optional[bool] = None     ,						_A							:							Optional[Union[str, TensorType]] = None     ,						**_A							:							str     ,						):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	List[str]					=		isinstance(_A     ,						np.ndarray ) and len(speech.shape ) > 1
       if is_batched_numpy and len(speech.shape ) > 2:
         raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' )
       __SCREAMING_SNAKE_CASE      :	int					=		is_batched_numpy or (
           isinstance(_A     ,						(list, tuple) ) and (isinstance(speech[0]     ,						(np.ndarray, tuple, list) ))
       )

       if is_batched:
         __SCREAMING_SNAKE_CASE      :	Tuple					=		[np.asarray(_A     ,						dtype=np.floataa ) for speech in speech]
       elif not is_batched and not isinstance(_A     ,						np.ndarray ):
         __SCREAMING_SNAKE_CASE      :	Any					=		np.asarray(_A     ,						dtype=np.floataa )
       elif isinstance(_A     ,						np.ndarray ) and speech.dtype is np.dtype(np.floataa ):
         __SCREAMING_SNAKE_CASE      :	Tuple					=		speech.astype(np.floataa )

       # always return batch
       if not is_batched:
         __SCREAMING_SNAKE_CASE      :	Optional[int]					=		[speech]

       # needed to make pad() work on spectrogram inputs
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		self.feature_size

       # convert into correct format for padding
       if is_target:
         __SCREAMING_SNAKE_CASE      :	Tuple					=		[self._extract_mel_features(_A ) for waveform in speech]
         __SCREAMING_SNAKE_CASE      :	Tuple					=		BatchFeature({'''input_values''': features} )
         __SCREAMING_SNAKE_CASE      :	Any					=		self.num_mel_bins
       else:
         __SCREAMING_SNAKE_CASE      :	Dict					=		BatchFeature({'''input_values''': speech} )

       __SCREAMING_SNAKE_CASE      :	Dict					=		self.pad(
           _A     ,						padding=_A     ,						max_length=_A     ,						truncation=_A     ,						pad_to_multiple_of=_A     ,						return_attention_mask=_A     ,						**_A     ,						)

       __SCREAMING_SNAKE_CASE      :	List[Any]					=		feature_size_hack

       # convert input values to correct format
       __SCREAMING_SNAKE_CASE      :	str					=		padded_inputs['''input_values''']
       if not isinstance(input_values[0]     ,						np.ndarray ):
         __SCREAMING_SNAKE_CASE      :	Any					=		[np.asarray(_A     ,						dtype=np.floataa ) for array in input_values]
       elif (
           not isinstance(_A     ,						np.ndarray )
           and isinstance(input_values[0]     ,						np.ndarray )
           and input_values[0].dtype is np.dtype(np.floataa )
       ):
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		[array.astype(np.floataa ) for array in input_values]
       elif isinstance(_A     ,						np.ndarray ) and input_values.dtype is np.dtype(np.floataa ):
         __SCREAMING_SNAKE_CASE      :	Any					=		input_values.astype(np.floataa )

       # convert attention_mask to correct format
       __SCREAMING_SNAKE_CASE      :	List[str]					=		padded_inputs.get('''attention_mask''' )
       if attention_mask is not None:
         __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		[np.asarray(_A     ,						dtype=np.intaa ) for array in attention_mask]

       # zero-mean and unit-variance normalization
       if not is_target and self.do_normalize:
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		(
             attention_mask
             if self._get_padding_strategies(_A     ,						max_length=_A ) is not PaddingStrategy.DO_NOT_PAD
             else None
         )
         __SCREAMING_SNAKE_CASE      :	List[str]					=		self.zero_mean_unit_var_norm(
             padded_inputs['''input_values''']     ,						attention_mask=_A     ,						padding_value=self.padding_value )

       if return_tensors is not None:
         __SCREAMING_SNAKE_CASE      :	str					=		padded_inputs.convert_to_tensors(_A )

       return padded_inputs




     def  UpperCAmelCase__							(				self							:							Union[str, Any] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	str					=		super().to_dict()

       # Don't serialize these as they are derived from the other properties.
       __SCREAMING_SNAKE_CASE      :	int					=		['''window''', '''mel_filters''', '''sample_size''', '''sample_stride''', '''n_fft''', '''n_freqs''']
       for name in names:
         if name in output:
           del output[name]

       return output






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  lowerCAmelCase_    (				self    :						str		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()



 @property
 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       SCREAMING_SNAKE_CASE_      		=     1
       SCREAMING_SNAKE_CASE_      		=     3
       SCREAMING_SNAKE_CASE_      		=     (32, 32)

       SCREAMING_SNAKE_CASE_      		=     floats_tensor((batch_size, num_channels) + sizes							,							rng=random.Random(0		)		).to(_lowerCAmelCase		)
       return image



 @property
 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						Tuple		):
       torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						Optional[int]		):
       torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     RobertaSeriesConfig(
           hidden_size=32							,							project_dim=32							,							intermediate_size=37							,							layer_norm_eps=1E-05							,							num_attention_heads=4							,							num_hidden_layers=5							,							pad_token_id=1							,							vocab_size=5_006							,							)
       return RobertaSeriesModelWithTransformation(_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       def extract(*_lowerCAmelCase    :						Optional[int]							,							**_lowerCAmelCase    :						str		):





             class 			lowerCamelCase_				:


              '''simple docstring'''







              def __init__(				self    :						str		):
                    SCREAMING_SNAKE_CASE_      		=     torch.ones([0]		)




              def  lowerCAmelCase_    (				self    :						Union[str, Any]							,							_lowerCAmelCase    :						int		):
                    self.pixel_values.to(_lowerCAmelCase		)
                    return self


             return Out()

       return extract



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       SCREAMING_SNAKE_CASE_      		=     'cpu'  # ensure determinism for the device-dependent torch.Generator
       SCREAMING_SNAKE_CASE_      		=     self.dummy_cond_unet
       SCREAMING_SNAKE_CASE_      		=     PNDMScheduler(skip_prk_steps=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.dummy_vae
       SCREAMING_SNAKE_CASE_      		=     self.dummy_text_encoder
       SCREAMING_SNAKE_CASE_      		=     XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'		)
       SCREAMING_SNAKE_CASE_      		=     77

       SCREAMING_SNAKE_CASE_      		=     self.dummy_image.to(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     init_image / 2 + 0.5

       # make sure here that pndm scheduler skips prk
       SCREAMING_SNAKE_CASE_      		=     AltDiffusionImgaImgPipeline(
           unet=_lowerCAmelCase							,							scheduler=_lowerCAmelCase							,							vae=_lowerCAmelCase							,							text_encoder=_lowerCAmelCase							,							tokenizer=_lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							feature_extractor=self.dummy_extractor							,							)
       SCREAMING_SNAKE_CASE_      		=     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,							do_normalize=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe.to(_lowerCAmelCase		)
       alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     'A painting of a squirrel eating a burger'
       SCREAMING_SNAKE_CASE_      		=     torch.Generator(device=_lowerCAmelCase		).manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe(
           [prompt]							,							generator=_lowerCAmelCase							,							guidance_scale=6.0							,							num_inference_steps=2							,							output_type='np'							,							image=_lowerCAmelCase							,							)

       SCREAMING_SNAKE_CASE_      		=     output.images

       SCREAMING_SNAKE_CASE_      		=     torch.Generator(device=_lowerCAmelCase		).manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe(
           [prompt]							,							generator=_lowerCAmelCase							,							guidance_scale=6.0							,							num_inference_steps=2							,							output_type='np'							,							image=_lowerCAmelCase							,							return_dict=_lowerCAmelCase							,							)[0]

       SCREAMING_SNAKE_CASE_      		=     image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE_      		=     image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       SCREAMING_SNAKE_CASE_      		=     np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]		)

       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  lowerCAmelCase_    (				self    :						Tuple		):
       SCREAMING_SNAKE_CASE_      		=     self.dummy_cond_unet
       SCREAMING_SNAKE_CASE_      		=     PNDMScheduler(skip_prk_steps=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.dummy_vae
       SCREAMING_SNAKE_CASE_      		=     self.dummy_text_encoder
       SCREAMING_SNAKE_CASE_      		=     XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'		)
       SCREAMING_SNAKE_CASE_      		=     77

       SCREAMING_SNAKE_CASE_      		=     self.dummy_image.to(_lowerCAmelCase		)

       # put models in fp16
       SCREAMING_SNAKE_CASE_      		=     unet.half()
       SCREAMING_SNAKE_CASE_      		=     vae.half()
       SCREAMING_SNAKE_CASE_      		=     bert.half()

       # make sure here that pndm scheduler skips prk
       SCREAMING_SNAKE_CASE_      		=     AltDiffusionImgaImgPipeline(
           unet=_lowerCAmelCase							,							scheduler=_lowerCAmelCase							,							vae=_lowerCAmelCase							,							text_encoder=_lowerCAmelCase							,							tokenizer=_lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							feature_extractor=self.dummy_extractor							,							)
       SCREAMING_SNAKE_CASE_      		=     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,							do_normalize=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe.to(_lowerCAmelCase		)
       alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     'A painting of a squirrel eating a burger'
       SCREAMING_SNAKE_CASE_      		=     torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe(
           [prompt]							,							generator=_lowerCAmelCase							,							num_inference_steps=2							,							output_type='np'							,							image=_lowerCAmelCase							,							).images

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




 @unittest.skipIf(torch_device != 'cuda'							,							'This test requires a GPU'		)
 def  lowerCAmelCase_    (				self    :						str		):
       SCREAMING_SNAKE_CASE_      		=     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
       SCREAMING_SNAKE_CASE_      		=     init_image.resize((760, 504)		)

       SCREAMING_SNAKE_CASE_      		=     'BAAI/AltDiffusion'
       SCREAMING_SNAKE_CASE_      		=     AltDiffusionImgaImgPipeline.from_pretrained(
           _lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							)
       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)
       pipe.enable_attention_slicing()

       SCREAMING_SNAKE_CASE_      		=     'A fantasy landscape, trending on artstation'

       SCREAMING_SNAKE_CASE_      		=     torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     pipe(
           prompt=_lowerCAmelCase							,							image=_lowerCAmelCase							,							strength=0.75							,							guidance_scale=7.5							,							generator=_lowerCAmelCase							,							output_type='np'							,							)
       SCREAMING_SNAKE_CASE_      		=     output.images[0]

       SCREAMING_SNAKE_CASE_      		=     image[255:258, 383:386, -1]

       assert image.shape == (504, 760, 3)
       SCREAMING_SNAKE_CASE_      		=     np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]		)

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





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


 '''simple docstring'''







 def  lowerCAmelCase_    (				self    :						str		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




 def  lowerCAmelCase_    (				self    :						int		):
       SCREAMING_SNAKE_CASE_      		=     load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/img2img/sketch-mountains-input.jpg'		)
       SCREAMING_SNAKE_CASE_      		=     init_image.resize((768, 512)		)
       SCREAMING_SNAKE_CASE_      		=     load_numpy(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'		)

       SCREAMING_SNAKE_CASE_      		=     'BAAI/AltDiffusion'
       SCREAMING_SNAKE_CASE_      		=     AltDiffusionImgaImgPipeline.from_pretrained(
           _lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							)
       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)
       pipe.enable_attention_slicing()

       SCREAMING_SNAKE_CASE_      		=     'A fantasy landscape, trending on artstation'

       SCREAMING_SNAKE_CASE_      		=     torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     pipe(
           prompt=_lowerCAmelCase							,							image=_lowerCAmelCase							,							strength=0.75							,							guidance_scale=7.5							,							generator=_lowerCAmelCase							,							output_type='np'							,							)
       SCREAMING_SNAKE_CASE_      		=     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