


'''simple docstring'''



import math
from typing import Any, Callable, List, Optional, Tuple, Union

import numpy as np
import torch

from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor


if is_onnx_available():
      from ..onnx_utils import OnnxRuntimeModel

from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder


__UpperCAmelCase    :int				       =     logging.get_logger(__name__)  # pylint: disable=invalid-name

__UpperCAmelCase    :List[Any]				       =     2_5_6



class 			a       (	_a ):


     """simple docstring"""






     SCREAMING_SNAKE_CASE :				Dict							     =     ["melgan"]

     def __init__(       self  :	str							,				snake_case  :	SpectrogramNotesEncoder							,				snake_case  :	SpectrogramContEncoder							,				snake_case  :	TaFilmDecoder							,				snake_case  :	DDPMScheduler							,				snake_case  :	OnnxRuntimeModel if is_onnx_available() else Any							,				)		->							None:
          super().__init__()

          # From MELGAN
          __UpperCAmelCase			:				Tuple													=    math.log(1E-5    )  # Matches MelGAN training.
          __UpperCAmelCase			:				Dict													=    4.0  # Largest value for most examples
          __UpperCAmelCase			:				int													=    128

          self.register_modules(
              notes_encoder=snake_case							,				continuous_encoder=snake_case							,				decoder=snake_case							,				scheduler=snake_case							,				melgan=snake_case							,				)

     def 				lowerCamelCase__				(       self  :	Dict							,				snake_case  :	Dict							,				snake_case  :	str=(-1.0, 1.0)							,				snake_case  :	str=False    )		->							Optional[Any]:
          __UpperCAmelCase			:				Optional[Any]													=    output_range
          if clip:
               __UpperCAmelCase			:				Dict													=    torch.clip(snake_case							,				self.min_value							,				self.max_value    )
          # Scale to [0, 1].
          __UpperCAmelCase			:				Optional[Any]													=    (features - self.min_value) / (self.max_value - self.min_value)
          # Scale to [min_out, max_out].
          return zero_one * (max_out - min_out) + min_out

     def 				lowerCamelCase__				(       self  :	Optional[Any]							,				snake_case  :	List[Any]							,				snake_case  :	str=(-1.0, 1.0)							,				snake_case  :	Union[str, Any]=False    )		->							Any:
          __UpperCAmelCase			:				Optional[int]													=    input_range
          __UpperCAmelCase			:				Dict													=    torch.clip(snake_case							,				snake_case							,				snake_case    ) if clip else outputs
          # Scale to [0, 1].
          __UpperCAmelCase			:				Tuple													=    (outputs - min_out) / (max_out - min_out)
          # Scale to [self.min_value, self.max_value].
          return zero_one * (self.max_value - self.min_value) + self.min_value

     def 				lowerCamelCase__				(       self  :	Tuple							,				snake_case  :	Optional[int]							,				snake_case  :	Union[str, Any]							,				snake_case  :	Optional[int]    )		->							Dict:
          __UpperCAmelCase			:				Any													=    input_tokens > 0
          __UpperCAmelCase			:				Tuple													=    self.notes_encoder(
              encoder_input_tokens=snake_case							,				encoder_inputs_mask=snake_case    )

          __UpperCAmelCase			:				List[str]													=    self.continuous_encoder(
              encoder_inputs=snake_case							,				encoder_inputs_mask=snake_case    )

          return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]

     def 				lowerCamelCase__				(       self  :	List[str]							,				snake_case  :	Any							,				snake_case  :	List[Any]							,				snake_case  :	Optional[Any]    )		->							str:
          __UpperCAmelCase			:				List[str]													=    noise_time
          if not torch.is_tensor(snake_case    ):
               __UpperCAmelCase			:				Union[str, Any]													=    torch.tensor([timesteps]							,				dtype=torch.long							,				device=input_tokens.device    )
          elif torch.is_tensor(snake_case    ) and len(timesteps.shape    ) == 0:
               __UpperCAmelCase			:				Optional[Any]													=    timesteps[None].to(input_tokens.device    )

          # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
          __UpperCAmelCase			:				Optional[Any]													=    timesteps * torch.ones(input_tokens.shape[0]							,				dtype=timesteps.dtype							,				device=timesteps.device    )

          __UpperCAmelCase			:				Optional[int]													=    self.decoder(
              encodings_and_masks=snake_case							,				decoder_input_tokens=snake_case							,				decoder_noise_time=snake_case    )
          return logits






     @torch.no_grad()
     def __call__(       self  :	Optional[int]							,				snake_case  :	List[List[int]]							,				snake_case  :	Optional[torch.Generator] = None							,				snake_case  :	int = 100							,				snake_case  :	bool = True							,				snake_case  :	str = "numpy"							,				snake_case  :	Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,				snake_case  :	int = 1							,				)		->							Union[AudioPipelineOutput, Tuple]:
          if (callback_steps is None) or (
              callback_steps is not None and (not isinstance(snake_case							,				snake_case    ) or callback_steps <= 0)
          ):
               raise ValueError(
                   f'`callback_steps` has to be a positive integer but is {callback_steps} of type'
                   f' {type(snake_case    )}.'    )

          __UpperCAmelCase			:				Any													=    np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]							,				dtype=np.floataa    )
          __UpperCAmelCase			:				Any													=    np.zeros([1, 0, self.n_dims]							,				np.floataa    )
          __UpperCAmelCase			:				Any													=    torch.ones((1, TARGET_FEATURE_LENGTH)							,				dtype=snake_case							,				device=self.device    )

          for i, encoder_input_tokens in enumerate(snake_case    ):
               if i == 0:
                    __UpperCAmelCase			:				Optional[int]													=    torch.from_numpy(pred_mel[:1].copy()    ).to(
                        device=self.device							,				dtype=self.decoder.dtype    )
                    # The first chunk has no previous context.
                    __UpperCAmelCase			:				Optional[Any]													=    torch.zeros((1, TARGET_FEATURE_LENGTH)							,				dtype=snake_case							,				device=self.device    )
               else:
                    # The full song pipeline does not feed in a context feature, so the mask
                    # will be all 0s after the feature converter. Because we know we're
                    # feeding in a full context chunk from the previous prediction, set it
                    # to all 1s.
                    __UpperCAmelCase			:				Dict													=    ones

               __UpperCAmelCase			:				List[Any]													=    self.scale_features(
                   snake_case							,				output_range=[-1.0, 1.0]							,				clip=snake_case    )

               __UpperCAmelCase			:				List[Any]													=    self.encode(
                   input_tokens=torch.IntTensor([encoder_input_tokens]    ).to(device=self.device    )							,				continuous_inputs=snake_case							,				continuous_mask=snake_case							,				)

               # Sample encoder_continuous_inputs shaped gaussian noise to begin loop
               __UpperCAmelCase			:				List[Any]													=    randn_tensor(
                   shape=encoder_continuous_inputs.shape							,				generator=snake_case							,				device=self.device							,				dtype=self.decoder.dtype							,				)

               # set step values
               self.scheduler.set_timesteps(snake_case    )

               # Denoising diffusion loop
               for j, t in enumerate(self.progress_bar(self.scheduler.timesteps    )    ):
                    __UpperCAmelCase			:				Any													=    self.decode(
                        encodings_and_masks=snake_case							,				input_tokens=snake_case							,				noise_time=t / self.scheduler.config.num_train_timesteps							,				)

                    # Compute previous output: x_t -> x_t-1
                    __UpperCAmelCase			:				Dict													=    self.scheduler.step(snake_case							,				snake_case							,				snake_case							,				generator=snake_case    ).prev_sample

               __UpperCAmelCase			:				Dict													=    self.scale_to_features(snake_case							,				input_range=[-1.0, 1.0]    )
               __UpperCAmelCase			:				Tuple													=    mel[:1]
               __UpperCAmelCase			:				Optional[Any]													=    mel.cpu().float().numpy()

               __UpperCAmelCase			:				Dict													=    np.concatenate([full_pred_mel, pred_mel[:1]]							,				axis=1    )

               # call the callback, if provided
               if callback is not None and i % callback_steps == 0:
                    callback(snake_case							,				snake_case    )

               logger.info('''Generated segment'''							,				snake_case    )

          if output_type == "numpy" and not is_onnx_available():
               raise ValueError(
                   '''Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.'''    )
          elif output_type == "numpy" and self.melgan is None:
               raise ValueError(
                   '''Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.'''    )

          if output_type == "numpy":
               __UpperCAmelCase			:				Optional[int]													=    self.melgan(input_features=full_pred_mel.astype(np.floataa    )    )
          else:
               __UpperCAmelCase			:				Tuple													=    full_pred_mel

          if not return_dict:
               return (output,)

          return AudioPipelineOutput(audios=snake_case    )








'''simple docstring'''



def 			_a			(		_lowercase      :			list[list[int]]    ,      _lowercase      :			int    ,      _lowercase      :			int    ,      _lowercase      :			set						):





     '''simple docstring'''






     __UpperCAmelCase							,     __UpperCAmelCase			:				Any													=    len(_lowercase						), len(grid[0]						)
     if (
         min(_lowercase    ,      _lowercase						) < 0
         or row == row_length
         or col == col_length
         or (row, col) in visit
         or grid[row][col] == 1
     ):
          return 0
     if row == row_length - 1 and col == col_length - 1:
          return 1

     visit.add((row, col)						)

     __UpperCAmelCase			:				Optional[Any]													=    0
     count += depth_first_search(_lowercase    ,      row + 1    ,      _lowercase    ,      _lowercase						)
     count += depth_first_search(_lowercase    ,      row - 1    ,      _lowercase    ,      _lowercase						)
     count += depth_first_search(_lowercase    ,      _lowercase    ,      col + 1    ,      _lowercase						)
     count += depth_first_search(_lowercase    ,      _lowercase    ,      col - 1    ,      _lowercase						)

     visit.remove((row, col)						)
     return count


if __name__ == "__main__":
      import doctest

      doctest.testmod()