





import unittest

from transformers import (
    MODEL_FOR_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
    TextGenerationPipeline,
    logging,
    pipeline,
)
from transformers.testing_utils import (
    CaptureLogger,
    is_pipeline_test,
    require_accelerate,
    require_tf,
    require_torch,
    require_torch_gpu,
    require_torch_or_tf,
)

from .test_pipelines_common import ANY





@is_pipeline_test
@require_torch_or_tf
class 			lowerCAmelCase__( unittest.TestCase    ):






       '''simple docstring'''


       __snake_case 			=    MODEL_FOR_CAUSAL_LM_MAPPING
       __snake_case 			=    TF_MODEL_FOR_CAUSAL_LM_MAPPING




       @require_torch
       def     UpperCamelCase_			(      self							)			->     List[str]:
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							pipeline(task="text-generation"    ,						model="sshleifer/tiny-ctrl"    ,						framework="pt"							)
            # Using `do_sample=False` to force deterministic output
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							text_generator("This is a test"    ,						do_sample=__lowerCamelCase							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    {
                        "generated_text": (
                            "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope."
                            " oscope. FiliFili@@"
                        )
                    }
                ]    ,						)

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator(["This is a test", "This is a second test"]							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    [
                        {
                            "generated_text": (
                                "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope."
                                " oscope. FiliFili@@"
                            )
                        }
                    ],
                    [
                        {
                            "generated_text": (
                                "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy"
                                " oscope. oscope. FiliFili@@"
                            )
                        }
                    ],
                ]    ,						)

            _SCREAMING_SNAKE_CASE       :	str						    =							text_generator("This is a test"    ,						do_sample=__lowerCamelCase    ,						num_return_sequences=2    ,						return_tensors=__lowerCamelCase							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    {"generated_token_ids": ANY(__lowerCamelCase							)},
                    {"generated_token_ids": ANY(__lowerCamelCase							)},
                ]    ,						)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							text_generator.model.config.eos_token_id
            _SCREAMING_SNAKE_CASE       :	int						    =							"<pad>"
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator(
                ["This is a test", "This is a second test"]    ,						do_sample=__lowerCamelCase    ,						num_return_sequences=2    ,						batch_size=2    ,						return_tensors=__lowerCamelCase    ,						)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    [
                        {"generated_token_ids": ANY(__lowerCamelCase							)},
                        {"generated_token_ids": ANY(__lowerCamelCase							)},
                    ],
                    [
                        {"generated_token_ids": ANY(__lowerCamelCase							)},
                        {"generated_token_ids": ANY(__lowerCamelCase							)},
                    ],
                ]    ,						)




       @require_tf
       def     UpperCamelCase_			(      self							)			->     List[Any]:
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							pipeline(task="text-generation"    ,						model="sshleifer/tiny-ctrl"    ,						framework="tf"							)

            # Using `do_sample=False` to force deterministic output
            _SCREAMING_SNAKE_CASE       :	Dict						    =							text_generator("This is a test"    ,						do_sample=__lowerCamelCase							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    {
                        "generated_text": (
                            "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵"
                            " please,"
                        )
                    }
                ]    ,						)

            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							text_generator(["This is a test", "This is a second test"]    ,						do_sample=__lowerCamelCase							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    [
                        {
                            "generated_text": (
                                "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵"
                                " please,"
                            )
                        }
                    ],
                    [
                        {
                            "generated_text": (
                                "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes"
                                " Cannes 閲閲Cannes Cannes Cannes 攵 please,"
                            )
                        }
                    ],
                ]    ,						)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     Optional[Any]:
            _SCREAMING_SNAKE_CASE       :	Dict						    =							TextGenerationPipeline(model=__lowerCamelCase    ,						tokenizer=__lowerCamelCase							)
            return text_generator, ["This is a test", "Another test"]




       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							"Hello I believe in"
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							pipeline("text-generation"    ,						model="hf-internal-testing/tiny-random-gpt2"							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							text_generator(__lowerCamelCase							)
            self.assertEqual(
                __lowerCamelCase    ,						[{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}]    ,						)

            _SCREAMING_SNAKE_CASE       :	Dict						    =							text_generator(__lowerCamelCase    ,						stop_sequence=" fe"							)
            self.assertEqual(__lowerCamelCase    ,						[{"generated_text": "Hello I believe in fe"}]							)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     int:
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator.model
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator.tokenizer

            _SCREAMING_SNAKE_CASE       :	Any						    =							text_generator("This is a test"							)
            self.assertEqual(__lowerCamelCase    ,						[{"generated_text": ANY(__lowerCamelCase							)}]							)
            self.assertTrue(outputs[0]["generated_text"].startswith("This is a test"							)							)

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							text_generator("This is a test"    ,						return_full_text=__lowerCamelCase							)
            self.assertEqual(__lowerCamelCase    ,						[{"generated_text": ANY(__lowerCamelCase							)}]							)
            self.assertNotIn("This is a test"    ,						outputs[0]["generated_text"]							)

            _SCREAMING_SNAKE_CASE       :	Any						    =							pipeline(task="text-generation"    ,						model=__lowerCamelCase    ,						tokenizer=__lowerCamelCase    ,						return_full_text=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Dict						    =							text_generator("This is a test"							)
            self.assertEqual(__lowerCamelCase    ,						[{"generated_text": ANY(__lowerCamelCase							)}]							)
            self.assertNotIn("This is a test"    ,						outputs[0]["generated_text"]							)

            _SCREAMING_SNAKE_CASE       :	Any						    =							text_generator("This is a test"    ,						return_full_text=__lowerCamelCase							)
            self.assertEqual(__lowerCamelCase    ,						[{"generated_text": ANY(__lowerCamelCase							)}]							)
            self.assertTrue(outputs[0]["generated_text"].startswith("This is a test"							)							)

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator(["This is great !", "Something else"]    ,						num_return_sequences=2    ,						do_sample=__lowerCamelCase							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    [{"generated_text": ANY(__lowerCamelCase							)}, {"generated_text": ANY(__lowerCamelCase							)}],
                    [{"generated_text": ANY(__lowerCamelCase							)}, {"generated_text": ANY(__lowerCamelCase							)}],
                ]    ,						)

            if text_generator.tokenizer.pad_token is not None:
                 _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							text_generator(
                     ["This is great !", "Something else"]    ,						num_return_sequences=2    ,						batch_size=2    ,						do_sample=__lowerCamelCase							)
                 self.assertEqual(
                     __lowerCamelCase    ,						[
                         [{"generated_text": ANY(__lowerCamelCase							)}, {"generated_text": ANY(__lowerCamelCase							)}],
                         [{"generated_text": ANY(__lowerCamelCase							)}, {"generated_text": ANY(__lowerCamelCase							)}],
                     ]    ,						)

            with self.assertRaises(__lowerCamelCase							):
                 _SCREAMING_SNAKE_CASE       :	List[Any]						    =							text_generator("test"    ,						return_full_text=__lowerCamelCase    ,						return_text=__lowerCamelCase							)
            with self.assertRaises(__lowerCamelCase							):
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator("test"    ,						return_full_text=__lowerCamelCase    ,						return_tensors=__lowerCamelCase							)
            with self.assertRaises(__lowerCamelCase							):
                 _SCREAMING_SNAKE_CASE       :	Tuple						    =							text_generator("test"    ,						return_text=__lowerCamelCase    ,						return_tensors=__lowerCamelCase							)

            # Empty prompt is slighly special
            # it requires BOS token to exist.
            # Special case for Pegasus which will always append EOS so will
            # work even without BOS.
            if (
                text_generator.tokenizer.bos_token_id is not None
                or "Pegasus" in tokenizer.__class__.__name__
                or "Git" in model.__class__.__name__
            ):
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							text_generator(""							)
                 self.assertEqual(__lowerCamelCase    ,						[{"generated_text": ANY(__lowerCamelCase							)}]							)
            else:
                 with self.assertRaises((ValueError, AssertionError)							):
                      _SCREAMING_SNAKE_CASE       :	Any						    =							text_generator(""							)

            if text_generator.framework == "tf":
                 # TF generation does not support max_new_tokens, and it's impossible
                 # to control long generation with only max_length without
                 # fancy calculation, dismissing tests for now.
                 return
            # We don't care about infinite range models.
            # They already work.
            # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
            _SCREAMING_SNAKE_CASE       :	int						    =							["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"]
            if (
                tokenizer.model_max_length < 1_0_0_0_0
                and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
            ):
                 # Handling of large generations
                 with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError)							):
                      text_generator("This is a test" * 5_0_0    ,						max_new_tokens=2_0							)

                 _SCREAMING_SNAKE_CASE       :	Dict						    =							text_generator("This is a test" * 5_0_0    ,						handle_long_generation="hole"    ,						max_new_tokens=2_0							)
                 # Hole strategy cannot work
                 with self.assertRaises(__lowerCamelCase							):
                      text_generator(
                          "This is a test" * 5_0_0    ,						handle_long_generation="hole"    ,						max_new_tokens=tokenizer.model_max_length + 1_0    ,						)




       @require_torch
       @require_accelerate
       @require_torch_gpu
       def     UpperCamelCase_			(      self							)			->     Any:
            import torch

            # Classic `model_kwargs`
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							pipeline(
                model="hf-internal-testing/tiny-random-bloom"    ,						model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa}    ,						)
            self.assertEqual(pipe.model.device    ,						torch.device(0							)							)
            self.assertEqual(pipe.model.lm_head.weight.dtype    ,						torch.bfloataa							)
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							pipe("This is a test"							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    {
                        "generated_text": (
                            "This is a test test test test test test test test test test test test test test test test"
                            " test"
                        )
                    }
                ]    ,						)

            # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
            _SCREAMING_SNAKE_CASE       :	int						    =							pipeline(model="hf-internal-testing/tiny-random-bloom"    ,						device_map="auto"    ,						torch_dtype=torch.bfloataa							)
            self.assertEqual(pipe.model.device    ,						torch.device(0							)							)
            self.assertEqual(pipe.model.lm_head.weight.dtype    ,						torch.bfloataa							)
            _SCREAMING_SNAKE_CASE       :	Dict						    =							pipe("This is a test"							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    {
                        "generated_text": (
                            "This is a test test test test test test test test test test test test test test test test"
                            " test"
                        )
                    }
                ]    ,						)

            # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							pipeline(model="hf-internal-testing/tiny-random-bloom"    ,						device_map="auto"							)
            self.assertEqual(pipe.model.device    ,						torch.device(0							)							)
            self.assertEqual(pipe.model.lm_head.weight.dtype    ,						torch.floataa							)
            _SCREAMING_SNAKE_CASE       :	int						    =							pipe("This is a test"							)
            self.assertEqual(
                __lowerCamelCase    ,						[
                    {
                        "generated_text": (
                            "This is a test test test test test test test test test test test test test test test test"
                            " test"
                        )
                    }
                ]    ,						)




       @require_torch
       @require_torch_gpu
       def     UpperCamelCase_			(      self							)			->     str:
            import torch

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							pipeline(model="hf-internal-testing/tiny-random-bloom"    ,						device=0    ,						torch_dtype=torch.floataa							)
            pipe("This is a test"							)




       @require_torch
       @require_accelerate
       @require_torch_gpu
       def     UpperCamelCase_			(      self							)			->     Dict:
            import torch

            _SCREAMING_SNAKE_CASE       :	List[str]						    =							pipeline(model="hf-internal-testing/tiny-random-bloom"    ,						device_map="auto"    ,						torch_dtype=torch.floataa							)
            pipe("This is a test"    ,						do_sample=__lowerCamelCase    ,						top_p=0.5							)







       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            _SCREAMING_SNAKE_CASE       :	str						    =							"Hello world"
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							pipeline("text-generation"    ,						model="hf-internal-testing/tiny-random-gpt2"							)
            if text_generator.model.framework == "tf":
                 _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							logging.get_logger("transformers.generation.tf_utils"							)
            else:
                 _SCREAMING_SNAKE_CASE       :	int						    =							logging.get_logger("transformers.generation.utils"							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							"Both `max_new_tokens`"  # The beggining of the message to be checked in this test

            # Both are set by the user -> log warning
            with CaptureLogger(__lowerCamelCase							) as cl:
                 _SCREAMING_SNAKE_CASE       :	List[Any]						    =							text_generator(__lowerCamelCase    ,						max_length=1_0    ,						max_new_tokens=1							)
            self.assertIn(__lowerCamelCase    ,						cl.out							)

            # The user only sets one -> no warning
            with CaptureLogger(__lowerCamelCase							) as cl:
                 _SCREAMING_SNAKE_CASE       :	str						    =							text_generator(__lowerCamelCase    ,						max_new_tokens=1							)
            self.assertNotIn(__lowerCamelCase    ,						cl.out							)

            with CaptureLogger(__lowerCamelCase							) as cl:
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							text_generator(__lowerCamelCase    ,						max_length=1_0							)
            self.assertNotIn(__lowerCamelCase    ,						cl.out							)






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							)