






"""simple docstring"""





import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm
    import torch_xla.debug.metrics as met


class      _lowercase (     lowerCAmelCase						):


      def __init__(    self				:	Optional[Any]							,   *a				:	List[Any]							,   a				:	List[Any]=None							,   a				:	List[Any]=None							,   **a				:	Union[str, Any]						):





            """simple docstring"""







            super().__init__(*a							,   **a						)
            __snake_case      :    Tuple  			=eval_examples
            __snake_case      :    Optional[int]  			=post_process_function


      def _UpperCamelCase						(    self				:	Dict							,   a				:	List[str]=None							,   a				:	Optional[Any]=None							,   a				:	str=None							,   a				:	str = "eval"						):





            """simple docstring"""







            __snake_case      :    Any  			=self.eval_dataset if eval_dataset is None else eval_dataset
            __snake_case      :    Tuple  			=self.get_eval_dataloader(a						)
            __snake_case      :    str  			=self.eval_examples if eval_examples is None else eval_examples

            # Temporarily disable metric computation, we will do it in the loop here.
            __snake_case      :    Tuple  			=self.compute_metrics
            __snake_case      :    List[str]  			=None
            __snake_case      :    Any  			=self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
            __snake_case      :    List[str]  			=time.time()
            try:
                  __snake_case      :    Tuple  			=eval_loop(
                      a							,   description='''Evaluation'''							,   prediction_loss_only=True if compute_metrics is None else None							,   ignore_keys=a							,   metric_key_prefix=a							,   )
            finally:
                  __snake_case      :    Dict  			=compute_metrics
            __snake_case      :    Optional[int]  			=self.args.eval_batch_size * self.args.world_size
            if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
                  start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
            output.metrics.update(
                speed_metrics(
                    a							,   a							,   num_samples=output.num_samples							,   num_steps=math.ceil(output.num_samples / total_batch_size						)							,   )						)
            if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
                  # Only the main node write the results by default
                  __snake_case      :    List[str]  			=self.post_process_function(a							,   a							,   output.predictions						)
                  __snake_case      :    Tuple  			=self.compute_metrics(a						)

                  # Prefix all keys with metric_key_prefix + '_'
                  for key in list(metrics.keys()						):
                        if not key.startswith(f'''{metric_key_prefix}_'''						):
                              __snake_case      :    Any  			=metrics.pop(a						)
                  metrics.update(output.metrics						)
            else:
                  __snake_case      :    Any  			=output.metrics

            if self.args.should_log:
                  # Only the main node log the results by default
                  self.log(a						)

            if self.args.tpu_metrics_debug or self.args.debug:
                  # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
                  xm.master_print(met.metrics_report()						)

            __snake_case      :    Optional[Any]  			=self.callback_handler.on_evaluate(self.args							,   self.state							,   self.control							,   a						)
            return metrics







      def _UpperCamelCase						(    self				:	List[str]							,   a				:	Dict							,   a				:	Dict							,   a				:	List[Any]=None							,   a				:	str = "test"						):





            """simple docstring"""







            __snake_case      :    List[str]  			=self.get_test_dataloader(a						)

            # Temporarily disable metric computation, we will do it in the loop here.
            __snake_case      :    Tuple  			=self.compute_metrics
            __snake_case      :    Union[str, Any]  			=None
            __snake_case      :    Any  			=self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
            __snake_case      :    Tuple  			=time.time()
            try:
                  __snake_case      :    Union[str, Any]  			=eval_loop(
                      a							,   description='''Prediction'''							,   prediction_loss_only=True if compute_metrics is None else None							,   ignore_keys=a							,   metric_key_prefix=a							,   )
            finally:
                  __snake_case      :    List[Any]  			=compute_metrics
            __snake_case      :    List[str]  			=self.args.eval_batch_size * self.args.world_size
            if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
                  start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
            output.metrics.update(
                speed_metrics(
                    a							,   a							,   num_samples=output.num_samples							,   num_steps=math.ceil(output.num_samples / total_batch_size						)							,   )						)

            if self.post_process_function is None or self.compute_metrics is None:
                  return output

            __snake_case      :    str  			=self.post_process_function(a							,   a							,   output.predictions							,   '''predict'''						)
            __snake_case      :    Optional[int]  			=self.compute_metrics(a						)

            # Prefix all keys with metric_key_prefix + '_'
            for key in list(metrics.keys()						):
                  if not key.startswith(f'''{metric_key_prefix}_'''						):
                        __snake_case      :    Dict  			=metrics.pop(a						)
            metrics.update(output.metrics						)
            return PredictionOutput(predictions=predictions.predictions							,   label_ids=predictions.label_ids							,   metrics=a						)










"""simple docstring"""





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      _lowercase (     lowerCAmelCase						):
      _a   :     Optional[Any]								=   ['''vqvae''']


      def __init__(    self				:	Optional[Any]							,   a				:	AutoencoderKL							,   a				:	UNetaDConditionModel							,   a				:	Mel							,   a				:	Union[DDIMScheduler, DDPMScheduler]							,   ):





            """simple docstring"""







            super().__init__()
            self.register_modules(unet=a							,   scheduler=a							,   mel=a							,   vqvae=a						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            return 5_0 if isinstance(self.scheduler							,   a						) else 1_0_0_0


      @torch.no_grad()
      def __call__(    self				:	Optional[int]							,   a				:	int = 1							,   a				:	str = None							,   a				:	np.ndarray = None							,   a				:	int = 0							,   a				:	int = 0							,   a				:	int = None							,   a				:	torch.Generator = None							,   a				:	float = 0							,   a				:	float = 0							,   a				:	torch.Generator = None							,   a				:	float = 0							,   a				:	torch.Tensor = None							,   a				:	torch.Tensor = None							,   a				:	Optional[int]=True							,   ):





            """simple docstring"""







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

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

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

                  if start_step > 0:
                        __snake_case      :    str  			=self.scheduler.add_noise(a							,   a							,   self.scheduler.timesteps[start_step - 1]						)

                  __snake_case      :    Optional[Any]  			=(
                      self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
                  )
                  __snake_case      :    int  			=int(mask_start_secs * pixels_per_second						)
                  __snake_case      :    Any  			=int(mask_end_secs * pixels_per_second						)
                  __snake_case      :    Union[str, Any]  			=self.scheduler.add_noise(a							,   a							,   torch.tensor(self.scheduler.timesteps[start_step:]						)						)

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

                  if isinstance(self.scheduler							,   a						):
                        __snake_case      :    List[str]  			=self.scheduler.step(
                            model_output=a							,   timestep=a							,   sample=a							,   eta=a							,   generator=a							,   )['''prev_sample''']
                  else:
                        __snake_case      :    List[Any]  			=self.scheduler.step(
                            model_output=a							,   timestep=a							,   sample=a							,   generator=a							,   )['''prev_sample''']

                  if mask is not None:
                        if mask_start > 0:
                              __snake_case      :    Any  			=mask[:, step, :, :mask_start]
                        if mask_end > 0:
                              __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
                  __snake_case      :    str  			=1 / self.vqvae.config.scaling_factor * images
                  __snake_case      :    Optional[int]  			=self.vqvae.decode(a						)['''sample''']

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

            __snake_case      :    Union[str, Any]  			=[self.mel.image_to_audio(a						) for _ in images]
            if not return_dict:
                  return images, (self.mel.get_sample_rate(), audios)

            return BaseOutput(**AudioPipelineOutput(np.array(a						)[:, np.newaxis, :]						)							,   **ImagePipelineOutput(a						)						)


      @torch.no_grad()
      def _UpperCamelCase						(    self				:	int							,   a				:	List[Image.Image]							,   a				:	int = 5_0						):





            """simple docstring"""







            assert isinstance(self.scheduler							,   a						)
            self.scheduler.set_timesteps(a						)
            __snake_case      :    Dict  			=np.array(
                [np.frombuffer(image.tobytes()							,   dtype='''uint8'''						).reshape((1, image.height, image.width)						) for image in images]						)
            __snake_case      :    Any  			=(sample / 2_5_5) * 2 - 1
            __snake_case      :    Any  			=torch.Tensor(a						).to(self.device						)

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

            return sample







      @staticmethod
      def _UpperCamelCase						(    a				:	torch.Tensor							,   a				:	torch.Tensor							,   a				:	float						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=acos(torch.dot(torch.flatten(a						)							,   torch.flatten(a						)						) / torch.norm(a						) / torch.norm(a						)						)
            return sin((1 - alpha) * theta						) * xa / sin(a						) + sin(alpha * theta						) * xa / sin(a						)


