





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


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

__SCREAMING_SNAKE_CASE     :Optional[Any]       =				256







class   A_	(  lowerCAmelCase_			):
 _lowerCamelCase  : str           =							["""melgan"""]




 def __init__(					self       :    Any	,			snake_case_       :    SpectrogramNotesEncoder	,			snake_case_       :    SpectrogramContEncoder	,			snake_case_       :    TaFilmDecoder	,			snake_case_       :    DDPMScheduler	,			snake_case_       :    OnnxRuntimeModel if is_onnx_available() else Any	,			):
      super().__init__()

      # From MELGAN
      _UpperCAmelCase     							=   math.log(1e-5    )  # Matches MelGAN training.
      _UpperCAmelCase     							=   4.0  # Largest value for most examples
      _UpperCAmelCase     							=   1_2_8

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




 def      lowercase	(					self       :    List[str]	,			snake_case_       :    Any	,			snake_case_       :    int=(-1.0, 1.0)	,			snake_case_       :    List[Any]=False    ):
      _UpperCAmelCase							,  _UpperCAmelCase     							=   output_range
      if clip:
           _UpperCAmelCase     							=   torch.clip(snake_case_	,			self.min_value	,			self.max_value    )
      # Scale to [0, 1].
      _UpperCAmelCase     							=   (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      lowercase	(					self       :    List[Any]	,			snake_case_       :    Dict	,			snake_case_       :    Optional[Any]=(-1.0, 1.0)	,			snake_case_       :    Optional[Any]=False    ):
      _UpperCAmelCase							,  _UpperCAmelCase     							=   input_range
      _UpperCAmelCase     							=   torch.clip(snake_case_	,			snake_case_	,			snake_case_    ) if clip else outputs
      # Scale to [0, 1].
      _UpperCAmelCase     							=   (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      lowercase	(					self       :    Dict	,			snake_case_       :    Any	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    Optional[Any]    ):
      _UpperCAmelCase     							=   input_tokens > 0
      _UpperCAmelCase							,  _UpperCAmelCase     							=   self.notes_encoder(
          encoder_input_tokens=snake_case_	,			encoder_inputs_mask=snake_case_    )

      _UpperCAmelCase							,  _UpperCAmelCase     							=   self.continuous_encoder(
          encoder_inputs=snake_case_	,			encoder_inputs_mask=snake_case_    )

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




 def      lowercase	(					self       :    Optional[Any]	,			snake_case_       :    str	,			snake_case_       :    Any	,			snake_case_       :    str    ):
      _UpperCAmelCase     							=   noise_time
      if not torch.is_tensor(snake_case_    ):
           _UpperCAmelCase     							=   torch.tensor([timesteps]	,			dtype=torch.long	,			device=input_tokens.device    )
      elif torch.is_tensor(snake_case_    ) and len(timesteps.shape    ) == 0:
           _UpperCAmelCase     							=   timesteps[None].to(input_tokens.device    )

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

      _UpperCAmelCase     							=   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       :    List[str]	,			snake_case_       :    List[List[int]]	,			snake_case_       :    Optional[torch.Generator] = None	,			snake_case_       :    int = 1_0_0	,			snake_case_       :    bool = True	,			snake_case_       :    str = "numpy"	,			snake_case_       :    Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,			snake_case_       :    int = 1	,			):
      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     							=   np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]	,			dtype=np.floataa    )
      _UpperCAmelCase     							=   np.zeros([1, 0, self.n_dims]	,			np.floataa    )
      _UpperCAmelCase     							=   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     							=   torch.from_numpy(pred_mel[:1].copy()    ).to(
                    device=self.device	,			dtype=self.decoder.dtype    )
                # The first chunk has no previous context.
                _UpperCAmelCase     							=   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     							=   ones

           _UpperCAmelCase     							=   self.scale_features(
               snake_case_	,			output_range=[-1.0, 1.0]	,			clip=snake_case_    )

           _UpperCAmelCase     							=   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     							=   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     							=   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     							=   self.scheduler.step(snake_case_	,			snake_case_	,			snake_case_	,			generator=snake_case_    ).prev_sample

           _UpperCAmelCase     							=   self.scale_to_features(snake_case_	,			input_range=[-1.0, 1.0]    )
           _UpperCAmelCase     							=   mel[:1]
           _UpperCAmelCase     							=   mel.cpu().float().numpy()

           _UpperCAmelCase     							=   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     							=   self.melgan(input_features=full_pred_mel.astype(np.floataa    )    )
      else:
           _UpperCAmelCase     							=   full_pred_mel

      if not return_dict:
           return (output,)

      return AudioPipelineOutput(audios=snake_case_    )











'''simple docstring'''




import os

import pytest
import yaml

from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
    "files"			,     [
        ["full:README.md", "dataset_infos.json"],
        ["empty:README.md", "dataset_infos.json"],
        ["dataset_infos.json"],
        ["full:README.md"],
    ]			,     )
def 	UpperCAmelCase_							(					__lowercase							:      Any			,     __lowercase							:      int       )		->       int:


     '''simple docstring'''



     _UpperCAmelCase     							=   tmp_path_factory.mktemp("dset_infos_dir"       )
     if "full:README.md" in files:
          with open(dataset_infos_dir / "README.md"			,     "w"       ) as f:
               f.write("---\ndataset_info:\n  dataset_size: 42\n---"       )
     if "empty:README.md" in files:
          with open(dataset_infos_dir / "README.md"			,     "w"       ) as f:
               f.write(""       )
    # we want to support dataset_infos.json for backward compatibility
     if "dataset_infos.json" in files:
          with open(dataset_infos_dir / "dataset_infos.json"			,     "w"       ) as f:
               f.write("{\"default\": {\"dataset_size\": 42}}"       )
     _UpperCAmelCase     							=   DatasetInfosDict.from_directory(__lowercase       )
     assert dataset_infos
     assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
    "dataset_info"			,     [
        DatasetInfo(),
        DatasetInfo(
            description="foo"			,     features=Features({"a": Value("int32"       )}       )			,     builder_name="builder"			,     config_name="config"			,     version="1.0.0"			,     splits=[{"name": "train"}]			,     download_size=42			,     ),
    ]			,     )
def 	UpperCAmelCase_							(					__lowercase							:      Tuple			,     __lowercase							:      DatasetInfo       )		->       Any:


     '''simple docstring'''



     _UpperCAmelCase     							=   str(__lowercase       )
     dataset_info.write_to_directory(__lowercase       )
     _UpperCAmelCase     							=   DatasetInfo.from_directory(__lowercase       )
     assert dataset_info == reloaded
     assert os.path.exists(os.path.join(__lowercase			,     "dataset_info.json"       )       )
def 	UpperCAmelCase_							(					)		->       Optional[Any]:


     '''simple docstring'''



     _UpperCAmelCase     							=   DatasetInfo(
         description="foo"			,     citation="bar"			,     homepage="https://foo.bar"			,     license="CC0"			,     features=Features({"a": Value("int32"       )}       )			,     post_processed={}			,     supervised_keys=()			,     task_templates=[]			,     builder_name="builder"			,     config_name="config"			,     version="1.0.0"			,     splits=[{"name": "train", "num_examples": 42}]			,     download_checksums={}			,     download_size=1337			,     post_processing_size=442			,     dataset_size=1234			,     size_in_bytes=1337 + 442 + 1234			,     )
     _UpperCAmelCase     							=   dataset_info._to_yaml_dict()
     assert sorted(__lowercase       ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML       )
     for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
          assert key in dataset_info_yaml_dict
          assert isinstance(dataset_info_yaml_dict[key]			,     (list, dict, int, str)       )
     _UpperCAmelCase     							=   yaml.safe_dump(__lowercase       )
     _UpperCAmelCase     							=   yaml.safe_load(__lowercase       )
     assert dataset_info_yaml_dict == reloaded
def 	UpperCAmelCase_							(					)		->       Optional[int]:


     '''simple docstring'''



     _UpperCAmelCase     							=   DatasetInfo()
     _UpperCAmelCase     							=   dataset_info._to_yaml_dict()
     assert dataset_info_yaml_dict == {}






@pytest.mark.parametrize(
    "dataset_infos_dict"			,     [
        DatasetInfosDict(),
        DatasetInfosDict({"default": DatasetInfo()}       ),
        DatasetInfosDict({"my_config_name": DatasetInfo()}       ),
        DatasetInfosDict(
            {
                "default": DatasetInfo(
                    description="foo"			,     features=Features({"a": Value("int32"       )}       )			,     builder_name="builder"			,     config_name="config"			,     version="1.0.0"			,     splits=[{"name": "train"}]			,     download_size=42			,     )
            }       ),
        DatasetInfosDict(
            {
                "v1": DatasetInfo(dataset_size=42       ),
                "v2": DatasetInfo(dataset_size=1337       ),
            }       ),
    ]			,     )
def 	UpperCAmelCase_							(					__lowercase							:      int			,     __lowercase							:      DatasetInfosDict       )		->       Dict:


     '''simple docstring'''



     _UpperCAmelCase     							=   str(__lowercase       )
     dataset_infos_dict.write_to_directory(__lowercase       )
     _UpperCAmelCase     							=   DatasetInfosDict.from_directory(__lowercase       )

     # the config_name of the dataset_infos_dict take over the attribute
     for config_name, dataset_info in dataset_infos_dict.items():
          _UpperCAmelCase     							=   config_name
          # the yaml representation doesn't include fields like description or citation
          # so we just test that we can recover what we can from the yaml
          _UpperCAmelCase     							=   DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict()       )
     assert dataset_infos_dict == reloaded

     if dataset_infos_dict:
          assert os.path.exists(os.path.join(__lowercase			,     "README.md"       )       )




