






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


UpperCAmelCase     :     Any							=	logging.get_logger(__name__)


if is_vision_available():
     import PIL







class     __lowerCAmelCase	(   lowerCAmelCase__):
      _lowercase    : List[str]            =      ["pixel_values"]







      def __init__(   self		,				lowerCAmelCase__ = True		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = PILImageResampling.BICUBIC		,				lowerCAmelCase__ = True		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = True		,				lowerCAmelCase__ = 1 / 2_5_5		,				lowerCAmelCase__ = True		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = True		,				**lowerCAmelCase__		,				)       ->						str:



        '''simple docstring'''




        super().__init__(**a__							)
        a__     : List[Any]  =size if size is not None else {"shortest_edge": 2_2_4}
        a__     : List[str]  =get_size_dict(a__		,				default_to_square=a__							)
        a__     : List[str]  =crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
        a__     : List[Any]  =get_size_dict(a__		,				default_to_square=a__		,				param_name="crop_size"							)

        a__     : List[Any]  =do_resize
        a__     : Dict  =size
        a__     : List[Any]  =resample
        a__     : Dict  =do_center_crop
        a__     : List[Any]  =crop_size
        a__     : Optional[Any]  =do_rescale
        a__     : Optional[int]  =rescale_factor
        a__     : int  =do_normalize
        a__     : Any  =image_mean if image_mean is not None else OPENAI_CLIP_MEAN
        a__     : Tuple  =image_std if image_std is not None else OPENAI_CLIP_STD
        a__     : Dict  =do_convert_rgb







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = PILImageResampling.BICUBIC		,				lowerCAmelCase__ = None		,				**lowerCAmelCase__		,				)       ->						str:



        '''simple docstring'''




        a__     : Dict  =get_size_dict(a__		,				default_to_square=a__							)
        if "shortest_edge" not in size:
          raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''							)
        a__     : int  =get_resize_output_image_size(a__		,				size=size["shortest_edge"]		,				default_to_square=a__							)
        return resize(a__		,				size=a__		,				resample=a__		,				data_format=a__		,				**a__							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = None		,				**lowerCAmelCase__		,				)       ->						int:



        '''simple docstring'''




        a__     : Dict  =get_size_dict(a__							)
        if "height" not in size or "width" not in size:
          raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''							)
        return center_crop(a__		,				size=(size["height"], size["width"])		,				data_format=a__		,				**a__							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = None		,				**lowerCAmelCase__		,				)       ->						Tuple:



        '''simple docstring'''




        return rescale(a__		,				scale=a__		,				data_format=a__		,				**a__							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = None		,				**lowerCAmelCase__		,				)       ->						List[Any]:



        '''simple docstring'''




        return normalize(a__		,				mean=a__		,				std=a__		,				data_format=a__		,				**a__							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = ChannelDimension.FIRST		,				**lowerCAmelCase__		,				)       ->						str:



        '''simple docstring'''




        a__     : Any  =do_resize if do_resize is not None else self.do_resize
        a__     : Union[str, Any]  =size if size is not None else self.size
        a__     : int  =get_size_dict(a__		,				param_name="size"		,				default_to_square=a__							)
        a__     : Optional[Any]  =resample if resample is not None else self.resample
        a__     : List[Any]  =do_center_crop if do_center_crop is not None else self.do_center_crop
        a__     : Union[str, Any]  =crop_size if crop_size is not None else self.crop_size
        a__     : Tuple  =get_size_dict(a__		,				param_name="crop_size"		,				default_to_square=a__							)
        a__     : int  =do_rescale if do_rescale is not None else self.do_rescale
        a__     : Tuple  =rescale_factor if rescale_factor is not None else self.rescale_factor
        a__     : List[Any]  =do_normalize if do_normalize is not None else self.do_normalize
        a__     : Tuple  =image_mean if image_mean is not None else self.image_mean
        a__     : List[Any]  =image_std if image_std is not None else self.image_std
        a__     : Any  =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        a__     : Dict  =make_list_of_images(a__							)

        if not valid_images(a__							):
          raise ValueError(
              "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
              "torch.Tensor, tf.Tensor or jax.ndarray."							)

        if do_resize and size is None:
          raise ValueError("Size must be specified if do_resize is True."							)

        if do_center_crop and crop_size is None:
          raise ValueError("Crop size must be specified if do_center_crop is True."							)

        if do_rescale and rescale_factor is None:
          raise ValueError("Rescale factor must be specified if do_rescale is True."							)

        if do_normalize and (image_mean is None or image_std is None):
          raise ValueError("Image mean and std must be specified if do_normalize is True."							)

        # PIL RGBA images are converted to RGB
        if do_convert_rgb:
          a__     : int  =[convert_to_rgb(a__							) for image in images]

        # All transformations expect numpy arrays.
        a__     : Union[str, Any]  =[to_numpy_array(a__							) for image in images]

        if do_resize:
          a__     : Optional[Any]  =[self.resize(image=a__		,				size=a__		,				resample=a__							) for image in images]

        if do_center_crop:
          a__     : List[Any]  =[self.center_crop(image=a__		,				size=a__							) for image in images]

        if do_rescale:
          a__     : List[str]  =[self.rescale(image=a__		,				scale=a__							) for image in images]

        if do_normalize:
          a__     : Any  =[self.normalize(image=a__		,				mean=a__		,				std=a__							) for image in images]

        a__     : List[str]  =[to_channel_dimension_format(a__		,				a__							) for image in images]

        a__     : Union[str, Any]  ={"pixel_values": images}
        return BatchFeature(data=a__		,				tensor_type=a__							)













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	(   UpperCamelCase__):
      _lowercase    : str            =      ["""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        _lowercase  (   self							)       ->						int:



        '''simple docstring'''




        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]]],
      ]:



        '''simple docstring'''




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

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

          if self.vqvae is not None:
            a__     : str  =self.vqvae.encode(torch.unsqueeze(lowerCAmelCase__		,				0							)							).latent_dist.sample(
                generator=lowerCAmelCase__							)[0]
            a__     : Any  =self.vqvae.config.scaling_factor * input_images

          if start_step > 0:
            a__     : Optional[int]  =self.scheduler.add_noise(lowerCAmelCase__		,				lowerCAmelCase__		,				self.scheduler.timesteps[start_step - 1]							)

          a__     : Tuple  =(
              self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
          )
          a__     : Union[str, Any]  =int(mask_start_secs * pixels_per_second							)
          a__     : List[str]  =int(mask_end_secs * pixels_per_second							)
          a__     : Optional[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__							):
            a__     : List[str]  =self.unet(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)["sample"]
          else:
            a__     : Optional[Any]  =self.unet(lowerCAmelCase__		,				lowerCAmelCase__							)["sample"]

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

          if mask is not None:
            if mask_start > 0:
              a__     : List[Any]  =mask[:, step, :, :mask_start]
            if mask_end > 0:
              a__     : Union[str, Any]  =mask[:, step, :, -mask_end:]

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

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

        a__     : str  =[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        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__ = 5_0							)       ->						np.ndarray:



        '''simple docstring'''




        assert isinstance(self.scheduler		,				lowerCAmelCase__							)
        self.scheduler.set_timesteps(lowerCAmelCase__							)
        a__     : Union[str, Any]  =np.array(
            [np.frombuffer(image.tobytes()		,				dtype="uint8"							).reshape((1, image.height, image.width)							) for image in images]							)
        a__     : Tuple  =(sample / 2_5_5) * 2 - 1
        a__     : List[Any]  =torch.Tensor(lowerCAmelCase__							).to(self.device							)

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

        return sample







      @staticmethod
      def        _lowercase  (   lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						torch.Tensor:



        '''simple docstring'''




        a__     : 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__							)






