





import argparse
import json

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    VideoMAEConfig,
    VideoMAEForPreTraining,
    VideoMAEForVideoClassification,
    VideoMAEImageProcessor,
)






def     lowerCamelCase__			(__lowerCamelCase	):
     _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							VideoMAEConfig()

     set_architecture_configs(__lowerCamelCase,       __lowerCamelCase	)

     if "finetuned" not in model_name:
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							False

     if "finetuned" in model_name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							"huggingface/label-files"
          if "kinetics" in model_name:
               _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							400
               _SCREAMING_SNAKE_CASE       :	List[str]						    =							"kinetics400-id2label.json"
          elif "ssv2" in model_name:
               _SCREAMING_SNAKE_CASE       :	int						    =							174
               _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							"something-something-v2-id2label.json"
          else:
               raise ValueError("Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned."	)
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							json.load(open(hf_hub_download(__lowerCamelCase,       __lowerCamelCase,       repo_type="dataset"	),       "r"	)	)
          _SCREAMING_SNAKE_CASE       :	Any						    =							{int(__lowerCamelCase	): v for k, v in idalabel.items()}
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							idalabel
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							{v: k for k, v in idalabel.items()}

     return config






def     lowerCamelCase__			(__lowerCamelCase,       __lowerCamelCase	):
     if "small" in model_name:
          _SCREAMING_SNAKE_CASE       :	Dict						    =							384
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							1536
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							12
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							16
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							12
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							3
          _SCREAMING_SNAKE_CASE       :	str						    =							192
          _SCREAMING_SNAKE_CASE       :	Dict						    =							768
     elif "large" in model_name:
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							1024
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							4096
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							24
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							16
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							12
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							8
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							512
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							2048
     elif "huge" in model_name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							1280
          _SCREAMING_SNAKE_CASE       :	str						    =							5120
          _SCREAMING_SNAKE_CASE       :	str						    =							32
          _SCREAMING_SNAKE_CASE       :	str						    =							16
          _SCREAMING_SNAKE_CASE       :	str						    =							12
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							8
          _SCREAMING_SNAKE_CASE       :	str						    =							640
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							2560
     elif "base" not in model_name:
          raise ValueError("Model name should include either \"small\", \"base\", \"large\", or \"huge\""	)






def     lowerCamelCase__			(__lowerCamelCase	):
     if "encoder." in name:
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							name.replace("encoder.",       ""	)
     if "cls_token" in name:
          _SCREAMING_SNAKE_CASE       :	str						    =							name.replace("cls_token",       "videomae.embeddings.cls_token"	)
     if "decoder_pos_embed" in name:
          _SCREAMING_SNAKE_CASE       :	Any						    =							name.replace("decoder_pos_embed",       "decoder.decoder_pos_embed"	)
     if "pos_embed" in name and "decoder" not in name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							name.replace("pos_embed",       "videomae.embeddings.position_embeddings"	)
     if "patch_embed.proj" in name:
          _SCREAMING_SNAKE_CASE       :	Any						    =							name.replace("patch_embed.proj",       "videomae.embeddings.patch_embeddings.projection"	)
     if "patch_embed.norm" in name:
          _SCREAMING_SNAKE_CASE       :	Dict						    =							name.replace("patch_embed.norm",       "videomae.embeddings.norm"	)
     if "decoder.blocks" in name:
          _SCREAMING_SNAKE_CASE       :	Any						    =							name.replace("decoder.blocks",       "decoder.decoder_layers"	)
     if "blocks" in name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							name.replace("blocks",       "videomae.encoder.layer"	)
     if "attn.proj" in name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							name.replace("attn.proj",       "attention.output.dense"	)
     if "attn" in name and "bias" not in name:
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							name.replace("attn",       "attention.self"	)
     if "attn" in name:
          _SCREAMING_SNAKE_CASE       :	Any						    =							name.replace("attn",       "attention.attention"	)
     if "norm1" in name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							name.replace("norm1",       "layernorm_before"	)
     if "norm2" in name:
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							name.replace("norm2",       "layernorm_after"	)
     if "mlp.fc1" in name:
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							name.replace("mlp.fc1",       "intermediate.dense"	)
     if "mlp.fc2" in name:
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							name.replace("mlp.fc2",       "output.dense"	)
     if "decoder_embed" in name:
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							name.replace("decoder_embed",       "decoder.decoder_embed"	)
     if "decoder_norm" in name:
          _SCREAMING_SNAKE_CASE       :	int						    =							name.replace("decoder_norm",       "decoder.decoder_norm"	)
     if "decoder_pred" in name:
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							name.replace("decoder_pred",       "decoder.decoder_pred"	)
     if "norm.weight" in name and "decoder" not in name and "fc" not in name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							name.replace("norm.weight",       "videomae.layernorm.weight"	)
     if "norm.bias" in name and "decoder" not in name and "fc" not in name:
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							name.replace("norm.bias",       "videomae.layernorm.bias"	)
     if "head" in name and "decoder" not in name:
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							name.replace("head",       "classifier"	)

     return name






def     lowerCamelCase__			(__lowerCamelCase,       __lowerCamelCase	):
     for key in orig_state_dict.copy().keys():
          _SCREAMING_SNAKE_CASE       :	Dict						    =							orig_state_dict.pop(__lowerCamelCase	)

          if key.startswith("encoder."	):
               _SCREAMING_SNAKE_CASE       :	List[str]						    =							key.replace("encoder.",       ""	)

          if "qkv" in key:
               _SCREAMING_SNAKE_CASE       :	Tuple						    =							key.split("."	)
               if key.startswith("decoder.blocks"	):
                    _SCREAMING_SNAKE_CASE       :	int						    =							config.decoder_hidden_size
                    _SCREAMING_SNAKE_CASE       :	str						    =							int(key_split[2]	)
                    _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							"decoder.decoder_layers."
                    if "weight" in key:
                         _SCREAMING_SNAKE_CASE       :	int						    =							val[:dim, :]
                         _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							val[dim : dim * 2, :]
                         _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							val[-dim:, :]
               else:
                    _SCREAMING_SNAKE_CASE       :	List[str]						    =							config.hidden_size
                    _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							int(key_split[1]	)
                    _SCREAMING_SNAKE_CASE       :	Dict						    =							"videomae.encoder.layer."
                    if "weight" in key:
                         _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							val[:dim, :]
                         _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							val[dim : dim * 2, :]
                         _SCREAMING_SNAKE_CASE       :	int						    =							val[-dim:, :]
          else:
               _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							val

     return orig_state_dict






def     lowerCamelCase__			():
     _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							hf_hub_download(
         repo_id="hf-internal-testing/spaghetti-video",       filename="eating_spaghetti.npy",       repo_type="dataset"	)
     _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							np.load(__lowerCamelCase	)
     return list(__lowerCamelCase	)






def     lowerCamelCase__			(__lowerCamelCase,       __lowerCamelCase,       __lowerCamelCase,       __lowerCamelCase	):
     _SCREAMING_SNAKE_CASE       :	Dict						    =							get_videomae_config(__lowerCamelCase	)

     if "finetuned" in model_name:
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							VideoMAEForVideoClassification(__lowerCamelCase	)
     else:
          _SCREAMING_SNAKE_CASE       :	str						    =							VideoMAEForPreTraining(__lowerCamelCase	)

     # download original checkpoint, hosted on Google Drive
     _SCREAMING_SNAKE_CASE       :	Dict						    =							"pytorch_model.bin"
     gdown.cached_download(__lowerCamelCase,       __lowerCamelCase,       quiet=__lowerCamelCase	)
     _SCREAMING_SNAKE_CASE       :	Dict						    =							torch.load(__lowerCamelCase,       map_location="cpu"	)
     if "model" in files:
          _SCREAMING_SNAKE_CASE       :	Dict						    =							files["model"]
     else:
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							files["module"]
     _SCREAMING_SNAKE_CASE       :	int						    =							convert_state_dict(__lowerCamelCase,       __lowerCamelCase	)

     model.load_state_dict(__lowerCamelCase	)
     model.eval()

     # verify model on basic input
     _SCREAMING_SNAKE_CASE       :	Any						    =							VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5],       image_std=[0.5, 0.5, 0.5]	)
     _SCREAMING_SNAKE_CASE       :	Any						    =							prepare_video()
     _SCREAMING_SNAKE_CASE       :	Tuple						    =							image_processor(__lowerCamelCase,       return_tensors="pt"	)

     if "finetuned" not in model_name:
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos",       filename="bool_masked_pos.pt"	)
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.load(__lowerCamelCase	)

     _SCREAMING_SNAKE_CASE       :	List[str]						    =							model(**__lowerCamelCase	)
     _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							outputs.logits

     _SCREAMING_SNAKE_CASE       :	int						    =							[
         "videomae-small-finetuned-kinetics",
         "videomae-small-finetuned-ssv2",
         # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
         "videomae-base-short",
         "videomae-base-short-finetuned-kinetics",
         "videomae-base",
         "videomae-base-finetuned-kinetics",
         "videomae-large",
         "videomae-large-finetuned-kinetics",
         "videomae-huge-finetuned-kinetics",
         # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
         "videomae-base-short-ssv2",
         "videomae-base-short-finetuned-ssv2",
         "videomae-base-ssv2",
         "videomae-base-finetuned-ssv2",
     ]

     # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
     if model_name == "videomae-small-finetuned-kinetics":
          _SCREAMING_SNAKE_CASE       :	Dict						    =							torch.Size([1, 400]	)
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							torch.tensor([-0.9291, -0.4061, -0.9307]	)
     elif model_name == "videomae-small-finetuned-ssv2":
          _SCREAMING_SNAKE_CASE       :	int						    =							torch.Size([1, 174]	)
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							torch.tensor([0.2671, -0.4689, -0.8235]	)
     elif model_name == "videomae-base":
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							torch.Size([1, 1408, 1536]	)
          _SCREAMING_SNAKE_CASE       :	str						    =							torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]]	)
     elif model_name == "videomae-base-short":
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.Size([1, 1408, 1536]	)
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]]	)
          # we verified the loss both for normalized and unnormalized targets for this one
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.tensor([0.5142]	) if config.norm_pix_loss else torch.tensor([0.6469]	)
     elif model_name == "videomae-large":
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							torch.Size([1, 1408, 1536]	)
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]]	)
     elif model_name == "videomae-large-finetuned-kinetics":
          _SCREAMING_SNAKE_CASE       :	Dict						    =							torch.Size([1, 400]	)
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							torch.tensor([0.0771, 0.0011, -0.3625]	)
     elif model_name == "videomae-huge-finetuned-kinetics":
          _SCREAMING_SNAKE_CASE       :	Any						    =							torch.Size([1, 400]	)
          _SCREAMING_SNAKE_CASE       :	Any						    =							torch.tensor([0.2433, 0.1632, -0.4894]	)
     elif model_name == "videomae-base-short-finetuned-kinetics":
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							torch.Size([1, 400]	)
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							torch.tensor([0.6588, 0.0990, -0.2493]	)
     elif model_name == "videomae-base-finetuned-kinetics":
          _SCREAMING_SNAKE_CASE       :	Tuple						    =							torch.Size([1, 400]	)
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							torch.tensor([0.3669, -0.0688, -0.2421]	)
     elif model_name == "videomae-base-short-ssv2":
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							torch.Size([1, 1408, 1536]	)
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]]	)
     elif model_name == "videomae-base-short-finetuned-ssv2":
          _SCREAMING_SNAKE_CASE       :	int						    =							torch.Size([1, 174]	)
          _SCREAMING_SNAKE_CASE       :	List[Any]						    =							torch.tensor([-0.0537, -0.1539, -0.3266]	)
     elif model_name == "videomae-base-ssv2":
          _SCREAMING_SNAKE_CASE       :	str						    =							torch.Size([1, 1408, 1536]	)
          _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]]	)
     elif model_name == "videomae-base-finetuned-ssv2":
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							torch.Size([1, 174]	)
          _SCREAMING_SNAKE_CASE       :	str						    =							torch.tensor([0.1961, -0.8337, -0.6389]	)
     else:
          raise ValueError(f"""Model name not supported. Should be one of {model_names}"""	)

     # verify logits
     assert logits.shape == expected_shape
     if "finetuned" in model_name:
          assert torch.allclose(logits[0, :3],       __lowerCamelCase,       atol=1e-4	)
     else:
          print("Logits:",       logits[0, :3, :3]	)
          assert torch.allclose(logits[0, :3, :3],       __lowerCamelCase,       atol=1e-4	)
     print("Logits ok!"	)

     # verify loss, if applicable
     if model_name == "videomae-base-short":
          _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							outputs.loss
          assert torch.allclose(__lowerCamelCase,       __lowerCamelCase,       atol=1e-4	)
          print("Loss ok!"	)

     if pytorch_dump_folder_path is not None:
          print(f"""Saving model and image processor to {pytorch_dump_folder_path}"""	)
          image_processor.save_pretrained(__lowerCamelCase	)
          model.save_pretrained(__lowerCamelCase	)

     if push_to_hub:
          print("Pushing to the hub..."	)
          model.push_to_hub(__lowerCamelCase,       organization="nielsr"	)


if __name__ == "__main__":
       UpperCamelCase__      =argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           '--checkpoint_url',
           default='https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4',
           type=str,
           help=(
               'URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct'
               ' download link.'
           ),
       )
       parser.add_argument(
           '--pytorch_dump_folder_path',
           default='/Users/nielsrogge/Documents/VideoMAE/Test',
           type=str,
           help='Path to the output PyTorch model directory.',
       )
       parser.add_argument('--model_name', default='videomae-base', type=str, help='Name of the model.')
       parser.add_argument(
           '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
       )

       UpperCamelCase__      =parser.parse_args()
       convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)






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 			lowerCAmelCase__( __lowercase    ):






       '''simple docstring'''


       __snake_case 			=    ['vqvae']




       def __init__(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						)			->     Optional[Any]:
            super().__init__()
            self.register_modules(unet=__lowerCamelCase    ,						scheduler=__lowerCamelCase    ,						mel=__lowerCamelCase    ,						vqvae=__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     int:
            return 5_0 if isinstance(self.scheduler    ,						__lowerCamelCase							) else 1_0_0_0




       @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]]],
       ]:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							steps or self.get_default_steps()
            self.scheduler.set_timesteps(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							step_generator or generator
            # For backwards compatibility
            if type(self.unet.config.sample_size							) == int:
                 _SCREAMING_SNAKE_CASE       :	Dict						    =							(self.unet.config.sample_size, self.unet.config.sample_size)
            if noise is None:
                 _SCREAMING_SNAKE_CASE       :	Tuple						    =							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    ,						)
            _SCREAMING_SNAKE_CASE       :	Any						    =							noise
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							None

            if audio_file is not None or raw_audio is not None:
                 self.mel.load_audio(__lowerCamelCase    ,						__lowerCamelCase							)
                 _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.mel.audio_slice_to_image(__lowerCamelCase							)
                 _SCREAMING_SNAKE_CASE       :	str						    =							np.frombuffer(input_image.tobytes()    ,						dtype="uint8"							).reshape(
                     (input_image.height, input_image.width)							)
                 _SCREAMING_SNAKE_CASE       :	List[Any]						    =							(input_image / 2_5_5) * 2 - 1
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.tensor(input_image[np.newaxis, :, :]    ,						dtype=torch.float							).to(self.device							)

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

                 if start_step > 0:
                      _SCREAMING_SNAKE_CASE       :	List[str]						    =							self.scheduler.add_noise(__lowerCamelCase    ,						__lowerCamelCase    ,						self.scheduler.timesteps[start_step - 1]							)

                 _SCREAMING_SNAKE_CASE       :	Dict						    =							(
                     self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
                 )
                 _SCREAMING_SNAKE_CASE       :	Dict						    =							int(mask_start_secs * pixels_per_second							)
                 _SCREAMING_SNAKE_CASE       :	str						    =							int(mask_end_secs * pixels_per_second							)
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							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							):
                      _SCREAMING_SNAKE_CASE       :	str						    =							self.unet(__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)["sample"]
                 else:
                      _SCREAMING_SNAKE_CASE       :	List[str]						    =							self.unet(__lowerCamelCase    ,						__lowerCamelCase							)["sample"]

                 if isinstance(self.scheduler    ,						__lowerCamelCase							):
                      _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.scheduler.step(
                          model_output=__lowerCamelCase    ,						timestep=__lowerCamelCase    ,						sample=__lowerCamelCase    ,						eta=__lowerCamelCase    ,						generator=__lowerCamelCase    ,						)["prev_sample"]
                 else:
                      _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.scheduler.step(
                          model_output=__lowerCamelCase    ,						timestep=__lowerCamelCase    ,						sample=__lowerCamelCase    ,						generator=__lowerCamelCase    ,						)["prev_sample"]

                 if mask is not None:
                      if mask_start > 0:
                           _SCREAMING_SNAKE_CASE       :	Tuple						    =							mask[:, step, :, :mask_start]
                      if mask_end > 0:
                           _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							mask[:, step, :, -mask_end:]

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

            _SCREAMING_SNAKE_CASE       :	Tuple						    =							(images / 2 + 0.5).clamp(0    ,						1							)
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							images.cpu().permute(0    ,						2    ,						3    ,						1							).numpy()
            _SCREAMING_SNAKE_CASE       :	int						    =							(images * 2_5_5).round().astype("uint8"							)
            _SCREAMING_SNAKE_CASE       :	Dict						    =							list(
                (Image.fromarray(_[:, :, 0]							) for _ in images)
                if images.shape[3] == 1
                else (Image.fromarray(__lowerCamelCase    ,						mode="RGB"							).convert("L"							) for _ in images)							)

            _SCREAMING_SNAKE_CASE       :	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     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase = 5_0							)			->     np.ndarray:
            assert isinstance(self.scheduler    ,						__lowerCamelCase							)
            self.scheduler.set_timesteps(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							np.array(
                [np.frombuffer(image.tobytes()    ,						dtype="uint8"							).reshape((1, image.height, image.width)							) for image in images]							)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							(sample / 2_5_5) * 2 - 1
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.Tensor(__lowerCamelCase							).to(self.device							)

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

            return sample







       @staticmethod
       def     UpperCamelCase_			(      __lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     torch.Tensor:
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							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							)