


import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu





class   __a			(    unittest.TestCase      ):
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[int]:




        '''simple docstring'''
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
 @property
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   Any  			=   1
        lowercase__:   List[Any]  			=   3
        lowercase__:   int  			=   (32, 32)

        lowercase__:   Dict  			=   floats_tensor((batch_size, num_channels) + sizes				, rng=random.Random(0 ) ).to(lowerCAmelCase__ )
        return image
 @property
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        torch.manual_seed(0 )
        lowercase__:   Tuple  			=   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 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        torch.manual_seed(0 )
        lowercase__:   int  			=   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 		SCREAMING_SNAKE_CASE__   (   self )					->				Any:




        '''simple docstring'''
        torch.manual_seed(0 )
        lowercase__:   Tuple  			=   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=1_000				, )
        return CLIPTextModel(lowerCAmelCase__ )
 @property
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        def extract(*lowerCAmelCase__				, **lowerCAmelCase__ ):





               class   __a			:
                def __init__(   self )					->				Dict:




                       '''simple docstring'''
                       lowercase__:   List[str]  			=   torch.ones([0] )
                def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				List[Any]:




                       '''simple docstring'''
                       self.pixel_values.to(lowerCAmelCase__ )
                       return self





               return Out()

        return extract
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   Any  			=   'cpu'  # ensure determinism for the device-dependent torch.Generator
        lowercase__:   Optional[Any]  			=   self.dummy_cond_unet
        lowercase__:   Union[str, Any]  			=   DDIMScheduler(
            beta_start=0.0_0_0_8_5				, beta_end=0.0_1_2				, beta_schedule='scaled_linear'				, clip_sample=lowerCAmelCase__				, set_alpha_to_one=lowerCAmelCase__				, )

        lowercase__:   Optional[Any]  			=   self.dummy_vae
        lowercase__:   Optional[Any]  			=   self.dummy_text_encoder
        lowercase__:   Union[str, Any]  			=   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

        # make sure here that pndm scheduler skips prk
        lowercase__:   Any  			=   StableDiffusionPipeline(
            unet=lowerCAmelCase__				, scheduler=lowerCAmelCase__				, vae=lowerCAmelCase__				, text_encoder=lowerCAmelCase__				, tokenizer=lowerCAmelCase__				, safety_checker=lowerCAmelCase__				, feature_extractor=self.dummy_extractor				, )
        lowercase__:   Any  			=   sd_pipe.to(lowerCAmelCase__ )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )

        lowercase__:   Any  			=   'A painting of a squirrel eating a burger'

        lowercase__:   Optional[int]  			=   torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 )
        lowercase__:   Optional[Any]  			=   sd_pipe([prompt]				, generator=lowerCAmelCase__				, guidance_scale=6.0				, num_inference_steps=2				, output_type='np' )
        lowercase__:   Tuple  			=   output.images

        lowercase__:   str  			=   torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 )
        lowercase__:   str  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=6.0				, num_inference_steps=2				, output_type='np'				, return_dict=lowerCAmelCase__				, )[0]

        lowercase__:   Union[str, Any]  			=   image[0, -3:, -3:, -1]
        lowercase__:   Union[str, Any]  			=   image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowercase__:   Union[str, Any]  			=   np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] )

        assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Any:




        '''simple docstring'''
        lowercase__:   Dict  			=   'cpu'  # ensure determinism for the device-dependent torch.Generator
        lowercase__:   Any  			=   self.dummy_cond_unet
        lowercase__:   Tuple  			=   PNDMScheduler(skip_prk_steps=lowerCAmelCase__ )
        lowercase__:   int  			=   self.dummy_vae
        lowercase__:   int  			=   self.dummy_text_encoder
        lowercase__:   List[Any]  			=   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

        # make sure here that pndm scheduler skips prk
        lowercase__:   int  			=   StableDiffusionPipeline(
            unet=lowerCAmelCase__				, scheduler=lowerCAmelCase__				, vae=lowerCAmelCase__				, text_encoder=lowerCAmelCase__				, tokenizer=lowerCAmelCase__				, safety_checker=lowerCAmelCase__				, feature_extractor=self.dummy_extractor				, )
        lowercase__:   str  			=   sd_pipe.to(lowerCAmelCase__ )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )

        lowercase__:   str  			=   'A painting of a squirrel eating a burger'
        lowercase__:   int  			=   torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 )
        lowercase__:   Dict  			=   sd_pipe([prompt]				, generator=lowerCAmelCase__				, guidance_scale=6.0				, num_inference_steps=2				, output_type='np' )

        lowercase__:   str  			=   output.images

        lowercase__:   List[Any]  			=   torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 )
        lowercase__:   List[str]  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=6.0				, num_inference_steps=2				, output_type='np'				, return_dict=lowerCAmelCase__				, )[0]

        lowercase__:   Optional[int]  			=   image[0, -3:, -3:, -1]
        lowercase__:   Dict  			=   image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowercase__:   List[Any]  			=   np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] )

        assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[str]:




        '''simple docstring'''
        lowercase__:   Tuple  			=   StableDiffusionPipeline.from_pretrained(
            'hf-internal-testing/tiny-stable-diffusion-lms-pipe'				, safety_checker=lowerCAmelCase__ )
        assert isinstance(lowerCAmelCase__				, lowerCAmelCase__ )
        assert isinstance(pipe.scheduler				, lowerCAmelCase__ )
        assert pipe.safety_checker is None

        lowercase__:   Optional[Any]  			=   pipe('example prompt'				, num_inference_steps=2 ).images[0]
        assert image is not None

        # check that there's no error when saving a pipeline with one of the models being None
        with tempfile.TemporaryDirectory() as tmpdirname:
               pipe.save_pretrained(lowerCAmelCase__ )
               lowercase__:   Optional[int]  			=   StableDiffusionPipeline.from_pretrained(lowerCAmelCase__ )

        # sanity check that the pipeline still works
        assert pipe.safety_checker is None
        lowercase__:   Dict  			=   pipe('example prompt'				, num_inference_steps=2 ).images[0]
        assert image is not None
 @unittest.skipIf(torch_device != 'cuda'				, 'This test requires a GPU' )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   self.dummy_cond_unet
        lowercase__:   Optional[Any]  			=   PNDMScheduler(skip_prk_steps=lowerCAmelCase__ )
        lowercase__:   Dict  			=   self.dummy_vae
        lowercase__:   Tuple  			=   self.dummy_text_encoder
        lowercase__:   Any  			=   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

        # put models in fp16
        lowercase__:   int  			=   unet.half()
        lowercase__:   Union[str, Any]  			=   vae.half()
        lowercase__:   Any  			=   bert.half()

        # make sure here that pndm scheduler skips prk
        lowercase__:   Tuple  			=   StableDiffusionPipeline(
            unet=lowerCAmelCase__				, scheduler=lowerCAmelCase__				, vae=lowerCAmelCase__				, text_encoder=lowerCAmelCase__				, tokenizer=lowerCAmelCase__				, safety_checker=lowerCAmelCase__				, feature_extractor=self.dummy_extractor				, )
        lowercase__:   Optional[Any]  			=   sd_pipe.to(lowerCAmelCase__ )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )

        lowercase__:   Any  			=   'A painting of a squirrel eating a burger'
        lowercase__:   Any  			=   sd_pipe([prompt]				, num_inference_steps=2				, output_type='np' ).images

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





@nightly
@require_torch_gpu
class   __a			(    unittest.TestCase      ):
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Any:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'				, safety_checker=lowerCAmelCase__ )
        lowercase__:   Tuple  			=   LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
        lowercase__:   str  			=   sd_pipe.to(lowerCAmelCase__ )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )

        lowercase__:   Tuple  			=   (
            'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'
            ' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'
            ' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'
            ' children from bahnhof zoo, detailed '
        )
        lowercase__:   Union[str, Any]  			=   4_003_660_346
        lowercase__:   Dict  			=   7

        # without safety guidance (sld_guidance_scale = 0)
        lowercase__:   Union[str, Any]  			=   torch.manual_seed(lowerCAmelCase__ )
        lowercase__:   Tuple  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=lowerCAmelCase__				, num_inference_steps=50				, output_type='np'				, width=512				, height=512				, sld_guidance_scale=0				, )

        lowercase__:   Optional[int]  			=   output.images
        lowercase__:   Optional[int]  			=   image[0, -3:, -3:, -1]
        lowercase__:   Any  			=   [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6]

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

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

        # without safety guidance (strong configuration)
        lowercase__:   List[Any]  			=   torch.manual_seed(lowerCAmelCase__ )
        lowercase__:   str  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=lowerCAmelCase__				, num_inference_steps=50				, output_type='np'				, width=512				, height=512				, sld_guidance_scale=2_000				, sld_warmup_steps=7				, sld_threshold=0.0_2_5				, sld_momentum_scale=0.5				, sld_mom_beta=0.7				, )

        lowercase__:   Optional[Any]  			=   output.images
        lowercase__:   Tuple  			=   image[0, -3:, -3:, -1]
        lowercase__:   str  			=   [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9]

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

        assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        lowercase__:   List[str]  			=   StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'				, safety_checker=lowerCAmelCase__ )
        lowercase__:   List[str]  			=   LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
        lowercase__:   int  			=   sd_pipe.to(lowerCAmelCase__ )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )

        lowercase__:   Dict  			=   'padme amidala taking a bath artwork, safe for work, no nudity'
        lowercase__:   Optional[Any]  			=   2_734_971_755
        lowercase__:   Dict  			=   7

        lowercase__:   Dict  			=   torch.manual_seed(lowerCAmelCase__ )
        lowercase__:   Optional[int]  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=lowerCAmelCase__				, num_inference_steps=50				, output_type='np'				, width=512				, height=512				, sld_guidance_scale=0				, )

        lowercase__:   Optional[int]  			=   output.images
        lowercase__:   Dict  			=   image[0, -3:, -3:, -1]
        lowercase__:   Optional[int]  			=   [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7]

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

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

        lowercase__:   Optional[int]  			=   torch.manual_seed(lowerCAmelCase__ )
        lowercase__:   Union[str, Any]  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=lowerCAmelCase__				, num_inference_steps=50				, output_type='np'				, width=512				, height=512				, sld_guidance_scale=2_000				, sld_warmup_steps=7				, sld_threshold=0.0_2_5				, sld_momentum_scale=0.5				, sld_mom_beta=0.7				, )

        lowercase__:   Tuple  			=   output.images
        lowercase__:   Union[str, Any]  			=   image[0, -3:, -3:, -1]
        lowercase__:   Tuple  			=   [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3]

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

        assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   List[str]  			=   StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' )
        lowercase__:   List[str]  			=   sd_pipe.to(lowerCAmelCase__ )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )

        lowercase__:   List[str]  			=   (
            'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'
            ' leyendecker'
        )
        lowercase__:   Union[str, Any]  			=   1_044_355_234
        lowercase__:   int  			=   12

        lowercase__:   List[str]  			=   torch.manual_seed(lowerCAmelCase__ )
        lowercase__:   int  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=lowerCAmelCase__				, num_inference_steps=50				, output_type='np'				, width=512				, height=512				, sld_guidance_scale=0				, )

        lowercase__:   Optional[int]  			=   output.images
        lowercase__:   str  			=   image[0, -3:, -3:, -1]
        lowercase__:   int  			=   np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] )

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

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

        lowercase__:   Union[str, Any]  			=   torch.manual_seed(lowerCAmelCase__ )
        lowercase__:   Optional[int]  			=   sd_pipe(
            [prompt]				, generator=lowerCAmelCase__				, guidance_scale=lowerCAmelCase__				, num_inference_steps=50				, output_type='np'				, width=512				, height=512				, sld_guidance_scale=2_000				, sld_warmup_steps=7				, sld_threshold=0.0_2_5				, sld_momentum_scale=0.5				, sld_mom_beta=0.7				, )

        lowercase__:   List[Any]  			=   output.images
        lowercase__:   Tuple  			=   image[0, -3:, -3:, -1]
        lowercase__:   Tuple  			=   np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] )
        assert image.shape == (1, 512, 512, 3)

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






from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel





class   __a			(    __UpperCamelCase      ):
 __lowercase :							Any        = ['vqvae']
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, )					->				Union[str, Any]:




        '''simple docstring'''
        super().__init__()
        self.register_modules(unet=lowerCAmelCase__				, scheduler=lowerCAmelCase__				, mel=lowerCAmelCase__				, vqvae=lowerCAmelCase__ )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        return 50 if isinstance(self.scheduler				, lowerCAmelCase__ ) else 1_000
 @torch.no_grad()
 def __call__(   self				, lowerCAmelCase__ = 1				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None				, lowerCAmelCase__ = 0				, lowerCAmelCase__ = 0				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None				, lowerCAmelCase__ = 0				, lowerCAmelCase__ = 0				, lowerCAmelCase__ = None				, lowerCAmelCase__ = 0				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None				, lowerCAmelCase__=True				, )					->				Union[
     Union[AudioPipelineOutput, ImagePipelineOutput],
     Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]],
 ]:




        '''simple docstring'''
        lowercase__:   Union[str, Any]  			=   steps or self.get_default_steps()
        self.scheduler.set_timesteps(lowerCAmelCase__ )
        lowercase__:   Optional[int]  			=   step_generator or generator
        # For backwards compatibility
        if type(self.unet.config.sample_size ) == int:
               lowercase__:   Optional[int]  			=   (self.unet.config.sample_size, self.unet.config.sample_size)
        if noise is None:
               lowercase__:   List[str]  			=   randn_tensor(
                   (
                       batch_size,
                       self.unet.config.in_channels,
                       self.unet.config.sample_size[0],
                       self.unet.config.sample_size[1],
                   )				, generator=lowerCAmelCase__				, device=self.device				, )
        lowercase__:   List[Any]  			=   noise
        lowercase__:   int  			=   None

        if audio_file is not None or raw_audio is not None:
               self.mel.load_audio(lowerCAmelCase__				, lowerCAmelCase__ )
               lowercase__:   int  			=   self.mel.audio_slice_to_image(lowerCAmelCase__ )
               lowercase__:   int  			=   np.frombuffer(input_image.tobytes()				, dtype='uint8' ).reshape(
                   (input_image.height, input_image.width) )
               lowercase__:   str  			=   (input_image / 255) * 2 - 1
               lowercase__:   Union[str, Any]  			=   torch.tensor(input_image[np.newaxis, :, :]				, dtype=torch.float ).to(self.device )

               if self.vqvae is not None:
                      lowercase__:   Optional[int]  			=   self.vqvae.encode(torch.unsqueeze(lowerCAmelCase__				, 0 ) ).latent_dist.sample(
                          generator=lowerCAmelCase__ )[0]
                      lowercase__:   Dict  			=   self.vqvae.config.scaling_factor * input_images

               if start_step > 0:
                      lowercase__:   List[Any]  			=   self.scheduler.add_noise(lowerCAmelCase__				, lowerCAmelCase__				, self.scheduler.timesteps[start_step - 1] )

               lowercase__:   str  			=   (
                   self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
               )
               lowercase__:   Dict  			=   int(mask_start_secs * pixels_per_second )
               lowercase__:   Tuple  			=   int(mask_end_secs * pixels_per_second )
               lowercase__:   List[Any]  			=   self.scheduler.add_noise(lowerCAmelCase__				, lowerCAmelCase__				, torch.tensor(self.scheduler.timesteps[start_step:] ) )

        for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ):
               if isinstance(self.unet				, lowerCAmelCase__ ):
                      lowercase__:   Union[str, Any]  			=   self.unet(lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )['sample']
               else:
                      lowercase__:   Optional[Any]  			=   self.unet(lowerCAmelCase__				, lowerCAmelCase__ )['sample']

               if isinstance(self.scheduler				, lowerCAmelCase__ ):
                      lowercase__:   List[str]  			=   self.scheduler.step(
                          model_output=lowerCAmelCase__				, timestep=lowerCAmelCase__				, sample=lowerCAmelCase__				, eta=lowerCAmelCase__				, generator=lowerCAmelCase__				, )['prev_sample']
               else:
                      lowercase__:   int  			=   self.scheduler.step(
                          model_output=lowerCAmelCase__				, timestep=lowerCAmelCase__				, sample=lowerCAmelCase__				, generator=lowerCAmelCase__				, )['prev_sample']

               if mask is not None:
                      if mask_start > 0:
                             lowercase__:   List[Any]  			=   mask[:, step, :, :mask_start]
                      if mask_end > 0:
                             lowercase__:   Optional[int]  			=   mask[:, step, :, -mask_end:]

        if self.vqvae is not None:
               # 0.18215 was scaling factor used in training to ensure unit variance
               lowercase__:   Union[str, Any]  			=   1 / self.vqvae.config.scaling_factor * images
               lowercase__:   Optional[Any]  			=   self.vqvae.decode(lowerCAmelCase__ )['sample']

        lowercase__:   Dict  			=   (images / 2 + 0.5).clamp(0				, 1 )
        lowercase__:   List[Any]  			=   images.cpu().permute(0				, 2				, 3				, 1 ).numpy()
        lowercase__:   int  			=   (images * 255).round().astype('uint8' )
        lowercase__:   Optional[Any]  			=   list(
            (Image.fromarray(_[:, :, 0] ) for _ in images)
            if images.shape[3] == 1
            else (Image.fromarray(lowerCAmelCase__				, mode='RGB' ).convert('L' ) for _ in images) )

        lowercase__:   Dict  			=   [self.mel.image_to_audio(lowerCAmelCase__ ) for _ in images]
        if not return_dict:
               return images, (self.mel.get_sample_rate(), audios)

        return BaseOutput(**AudioPipelineOutput(np.array(lowerCAmelCase__ )[:, np.newaxis, :] )				, **ImagePipelineOutput(lowerCAmelCase__ ) )
 @torch.no_grad()
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ = 50 )					->				np.ndarray:




        '''simple docstring'''
        assert isinstance(self.scheduler				, lowerCAmelCase__ )
        self.scheduler.set_timesteps(lowerCAmelCase__ )
        lowercase__:   List[str]  			=   np.array(
            [np.frombuffer(image.tobytes()				, dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] )
        lowercase__:   str  			=   (sample / 255) * 2 - 1
        lowercase__:   str  			=   torch.Tensor(lowerCAmelCase__ ).to(self.device )

        for t in self.progress_bar(torch.flip(self.scheduler.timesteps				, (0,) ) ):
               lowercase__:   Union[str, Any]  			=   t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
               lowercase__:   Optional[Any]  			=   self.scheduler.alphas_cumprod[t]
               lowercase__:   str  			=   (
                   self.scheduler.alphas_cumprod[prev_timestep]
                   if prev_timestep >= 0
                   else self.scheduler.final_alpha_cumprod
               )
               lowercase__:   str  			=   1 - alpha_prod_t
               lowercase__:   int  			=   self.unet(lowerCAmelCase__				, lowerCAmelCase__ )['sample']
               lowercase__:   int  			=   (1 - alpha_prod_t_prev) ** 0.5 * model_output
               lowercase__:   Optional[int]  			=   (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
               lowercase__:   Any  			=   sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

        return sample
 @staticmethod
 def 		SCREAMING_SNAKE_CASE__   (   lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				torch.Tensor:




        '''simple docstring'''
        lowercase__:   Any  			=   acos(torch.dot(torch.flatten(lowerCAmelCase__ )				, torch.flatten(lowerCAmelCase__ ) ) / torch.norm(lowerCAmelCase__ ) / torch.norm(lowerCAmelCase__ ) )
        return sin((1 - alpha) * theta ) * xa / sin(lowerCAmelCase__ ) + sin(alpha * theta ) * xa / sin(lowerCAmelCase__ )


