





"""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


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

a_			=      256






class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 _lowerCamelCase				=					["""melgan"""]

 def __init__(   self ,						__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase ,						):



     '''simple docstring'''




     super().__init__()

     # From MELGAN
     __A   :						List[Any]									=					math.log(1e-5  )  # Matches MelGAN training.
     __A   :						Any									=					4.0  # Largest value for most examples
     __A   :						Tuple									=					128

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

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=(-1.0, 1.0) ,						__lowerCamelCase=False  ):



     '''simple docstring'''




     __A			,	__A   :						str									=					output_range
     if clip:
         __A   :						Optional[Any]									=					torch.clip(__lowerCamelCase ,						self.min_value ,						self.max_value  )
     # Scale to [0, 1].
     __A   :						Union[str, 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  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=(-1.0, 1.0) ,						__lowerCamelCase=False  ):



     '''simple docstring'''




     __A			,	__A   :						List[Any]									=					input_range
     __A   :						Optional[Any]									=					torch.clip(__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase  ) if clip else outputs
     # Scale to [0, 1].
     __A   :						Any									=					(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  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Tuple									=					input_tokens > 0
     __A			,	__A   :						Dict									=					self.notes_encoder(
         encoder_input_tokens=__lowerCamelCase ,						encoder_inputs_mask=__lowerCamelCase  )

     __A			,	__A   :						Tuple									=					self.continuous_encoder(
         encoder_inputs=__lowerCamelCase ,						encoder_inputs_mask=__lowerCamelCase  )

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

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Tuple									=					noise_time
     if not torch.is_tensor(__lowerCamelCase  ):
         __A   :						str									=					torch.tensor([timesteps] ,						dtype=torch.long ,						device=input_tokens.device  )
     elif torch.is_tensor(__lowerCamelCase  ) and len(timesteps.shape  ) == 0:
         __A   :						int									=					timesteps[None].to(input_tokens.device  )

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

     __A   :						str									=					self.decoder(
         encodings_and_masks=__lowerCamelCase ,						decoder_input_tokens=__lowerCamelCase ,						decoder_noise_time=__lowerCamelCase  )
     return logits







 @torch.no_grad()
 def __call__(   self ,						__lowerCamelCase ,						__lowerCamelCase = None ,						__lowerCamelCase = 100 ,						__lowerCamelCase = True ,						__lowerCamelCase = "numpy" ,						__lowerCamelCase = None ,						__lowerCamelCase = 1 ,						):



     '''simple docstring'''




     if (callback_steps is None) or (
         callback_steps is not None and (not isinstance(__lowerCamelCase ,						__lowerCamelCase  ) or callback_steps <= 0)
     ):
         raise ValueError(
             F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
             F""" {type(__lowerCamelCase  )}."""  )

     __A   :						Optional[Any]									=					np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] ,						dtype=np.floataa  )
     __A   :						Tuple									=					np.zeros([1, 0, self.n_dims] ,						np.floataa  )
     __A   :						str									=					torch.ones((1, TARGET_FEATURE_LENGTH) ,						dtype=__lowerCamelCase ,						device=self.device  )

     for i, encoder_input_tokens in enumerate(__lowerCamelCase  ):
         if i == 0:
             __A   :						Union[str, Any]									=					torch.from_numpy(pred_mel[:1].copy()  ).to(
                 device=self.device ,						dtype=self.decoder.dtype  )
             # The first chunk has no previous context.
             __A   :						Tuple									=					torch.zeros((1, TARGET_FEATURE_LENGTH) ,						dtype=__lowerCamelCase ,						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.
             __A   :						Union[str, Any]									=					ones

         __A   :						Union[str, Any]									=					self.scale_features(
             __lowerCamelCase ,						output_range=[-1.0, 1.0] ,						clip=__lowerCamelCase  )

         __A   :						Dict									=					self.encode(
             input_tokens=torch.IntTensor([encoder_input_tokens]  ).to(device=self.device  ) ,						continuous_inputs=__lowerCamelCase ,						continuous_mask=__lowerCamelCase ,						)

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

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

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

             # Compute previous output: x_t -> x_t-1
             __A   :						Optional[Any]									=					self.scheduler.step(__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase ,						generator=__lowerCamelCase  ).prev_sample

         __A   :						str									=					self.scale_to_features(__lowerCamelCase ,						input_range=[-1.0, 1.0]  )
         __A   :						Any									=					mel[:1]
         __A   :						Dict									=					mel.cpu().float().numpy()

         __A   :						Any									=					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(__lowerCamelCase ,						__lowerCamelCase  )

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

     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":
         __A   :						Optional[int]									=					self.melgan(input_features=full_pred_mel.astype(np.floataa  )  )
     else:
         __A   :						Union[str, Any]									=					full_pred_mel

     if not return_dict:
         return (output,)

     return AudioPipelineOutput(audios=__lowerCamelCase  )











"""simple docstring"""



def 		__lowercase					(       )       ->Tuple:



    '''simple docstring'''







    __A   :						str									=					[]
    __A   :						List[Any]									=					1

    while len(snake_case_						) < 1e6:
        constant.append(str(snake_case_						)						)
        i += 1

    __A   :						Any									=					''''''.join(snake_case_						)

    return (
        int(constant[0]						)
        * int(constant[9]						)
        * int(constant[99]						)
        * int(constant[999]						)
        * int(constant[9999]						)
        * int(constant[99999]						)
        * int(constant[999999]						)
    )


if __name__ == "__main__":
       print(solution())




