


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


lowerCamelCase							:   Optional[Any]  						=	logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase							:   Dict  						=	256
class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      lowerCAmelCase__					:     List[Any]  					=							["""melgan"""]



      def __init__(self    :    Tuple   ,						UpperCamelCase    :    SpectrogramNotesEncoder   ,						UpperCamelCase    :    SpectrogramContEncoder   ,						UpperCamelCase    :    TaFilmDecoder   ,						UpperCamelCase    :    DDPMScheduler   ,						UpperCamelCase    :    OnnxRuntimeModel if is_onnx_available() else Any   ,						):

             '''simple docstring'''







             super().__init__()

             # From MELGAN
             lowercase__      			= math.log(1E-5 )  # Matches MelGAN training.
             lowercase__      			= 4.0  # Largest value for most examples
             lowercase__      			= 128

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



      def       UpperCamelCase__		(self    :    str   ,						UpperCamelCase    :    Dict   ,						UpperCamelCase    :    Tuple=(-1.0, 1.0)   ,						UpperCamelCase    :    int=False ):

             '''simple docstring'''







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

             '''simple docstring'''







             lowercase__			,lowercase__      			= input_range
             lowercase__      			= torch.clip(UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase ) if clip else outputs
             # Scale to [0, 1].
             lowercase__      			= (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    :    Dict   ,						UpperCamelCase    :    List[Any]   ,						UpperCamelCase    :    List[str]   ,						UpperCamelCase    :    Union[str, Any] ):

             '''simple docstring'''







             lowercase__      			= input_tokens > 0
             lowercase__			,lowercase__      			= self.notes_encoder(
                 encoder_input_tokens=UpperCamelCase   ,						encoder_inputs_mask=UpperCamelCase )

             lowercase__			,lowercase__      			= self.continuous_encoder(
                 encoder_inputs=UpperCamelCase   ,						encoder_inputs_mask=UpperCamelCase )

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



      def       UpperCamelCase__		(self    :    Dict   ,						UpperCamelCase    :    Union[str, Any]   ,						UpperCamelCase    :    Optional[int]   ,						UpperCamelCase    :    Any ):

             '''simple docstring'''







             lowercase__      			= noise_time
             if not torch.is_tensor(UpperCamelCase ):
                    lowercase__      			= torch.tensor([timesteps]   ,						dtype=torch.long   ,						device=input_tokens.device )
             elif torch.is_tensor(UpperCamelCase ) and len(timesteps.shape ) == 0:
                    lowercase__      			= timesteps[None].to(input_tokens.device )

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

             lowercase__      			= self.decoder(
                 encodings_and_masks=UpperCamelCase   ,						decoder_input_tokens=UpperCamelCase   ,						decoder_noise_time=UpperCamelCase )
             return logits






      @torch.no_grad()
      def __call__(self    :    List[Any]   ,						UpperCamelCase    :    List[List[int]]   ,						UpperCamelCase    :    Optional[torch.Generator] = None   ,						UpperCamelCase    :    int = 100   ,						UpperCamelCase    :    bool = True   ,						UpperCamelCase    :    str = "numpy"   ,						UpperCamelCase    :    Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,						UpperCamelCase    :    int = 1   ,						):

             '''simple docstring'''







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

             lowercase__      			= np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]   ,						dtype=np.floataa )
             lowercase__      			= np.zeros([1, 0, self.n_dims]   ,						np.floataa )
             lowercase__      			= torch.ones((1, TARGET_FEATURE_LENGTH)   ,						dtype=UpperCamelCase   ,						device=self.device )

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

                    lowercase__      			= self.scale_features(
                        UpperCamelCase   ,						output_range=[-1.0, 1.0]   ,						clip=UpperCamelCase )

                    lowercase__      			= self.encode(
                        input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device )   ,						continuous_inputs=UpperCamelCase   ,						continuous_mask=UpperCamelCase   ,						)

                    # Sample encoder_continuous_inputs shaped gaussian noise to begin loop
                    lowercase__      			= randn_tensor(
                        shape=encoder_continuous_inputs.shape   ,						generator=UpperCamelCase   ,						device=self.device   ,						dtype=self.decoder.dtype   ,						)

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

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

                           # Compute previous output: x_t -> x_t-1
                           lowercase__      			= self.scheduler.step(UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase   ,						generator=UpperCamelCase ).prev_sample

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

                    lowercase__      			= 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(UpperCamelCase   ,						UpperCamelCase )

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

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

             if not return_dict:
                    return (output,)

             return AudioPipelineOutput(audios=UpperCamelCase )








'''simple docstring'''

import os
import re
import warnings
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
 from .tokenization_ta import TaTokenizer
else:
 lowerCamelCase							:   Any  						=	None


lowerCamelCase							:   Dict  						=	logging.get_logger(__name__)

lowerCamelCase							:   Optional[int]  						=	{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

lowerCamelCase							:   List[str]  						=	{
    'vocab_file': {
        't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model',
        't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model',
        't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model',
        't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model',
        't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json',
        't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json',
        't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json',
        't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json',
        't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json',
    },
}


# TODO(PVP) - this should be removed in Transformers v5
lowerCamelCase							:   Any  						=	{
    't5-small': 512,
    't5-base': 512,
    't5-large': 512,
    't5-3b': 512,
    't5-11b': 512,
}
class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      lowerCAmelCase__					:     List[str]  					=							VOCAB_FILES_NAMES
      lowerCAmelCase__					:     str  					=							PRETRAINED_VOCAB_FILES_MAP
      lowerCAmelCase__					:     Optional[Any]  					=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      lowerCAmelCase__					:     int  					=							["""input_ids""", """attention_mask"""]
      lowerCAmelCase__					:     Optional[int]  					=							TaTokenizer

      lowerCAmelCase__					:     List[int]  					=							[]



      def __init__(self    :    Dict   ,						UpperCamelCase    :    str=None   ,						UpperCamelCase    :    Optional[Any]=None   ,						UpperCamelCase    :    Any="</s>"   ,						UpperCamelCase    :    str="<unk>"   ,						UpperCamelCase    :    List[str]="<pad>"   ,						UpperCamelCase    :    List[str]=100   ,						UpperCamelCase    :    Tuple=None   ,						**UpperCamelCase    :    List[str]   ,						):

             '''simple docstring'''







             if extra_ids > 0 and additional_special_tokens is None:
                    lowercase__      			= [f"<extra_id_{i}>" for i in range(UpperCamelCase )]
             elif extra_ids > 0 and additional_special_tokens is not None:
                    # Check that we have the right number of extra special tokens
                    lowercase__      			= len(set(filter(lambda UpperCamelCase : bool('''extra_id_''' in str(UpperCamelCase ) )   ,						UpperCamelCase ) ) )
                    if extra_tokens != extra_ids:
                           raise ValueError(
                               f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
                               ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
                               ''' tokens''' )

             super().__init__(
                 UpperCamelCase   ,						tokenizer_file=UpperCamelCase   ,						eos_token=UpperCamelCase   ,						unk_token=UpperCamelCase   ,						pad_token=UpperCamelCase   ,						extra_ids=UpperCamelCase   ,						additional_special_tokens=UpperCamelCase   ,						**UpperCamelCase   ,						)

             lowercase__      			= vocab_file
             lowercase__      			= False if not self.vocab_file else True
             lowercase__      			= extra_ids



      @staticmethod
      def       UpperCamelCase__		(UpperCamelCase    :    List[Any]   ,						UpperCamelCase    :    Union[str, Any]   ,						UpperCamelCase    :    Optional[Any] ):

             '''simple docstring'''







             if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes:
                    lowercase__      			= TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path]
                    if init_max_model_length is not None and init_max_model_length != max_model_length:
                           return init_max_model_length
                    elif init_max_model_length is None:
                           warnings.warn(
                               '''This tokenizer was incorrectly instantiated with a model max length of'''
                               f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"
                               ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
                               ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
                               f" {pretrained_model_name_or_path} automatically truncating your input to"
                               f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"
                               f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"
                               ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
                               ''' instantiate this tokenizer with `model_max_length` set to your preferred value.'''   ,						UpperCamelCase   ,						)

             return max_model_length



      def       UpperCamelCase__		(self    :    Any   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    Optional[str] = None ):

             '''simple docstring'''







             if not self.can_save_slow_tokenizer:
                    raise ValueError(
                        '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
                        '''tokenizer.''' )

             if not os.path.isdir(UpperCamelCase ):
                    logger.error(f"Vocabulary path ({save_directory}) should be a directory" )
                    return
             lowercase__      			= os.path.join(
                 UpperCamelCase   ,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )

             if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ):
                    copyfile(self.vocab_file   ,						UpperCamelCase )
                    logger.info(f"Copy vocab file to {out_vocab_file}" )

             return (out_vocab_file,)



      def       UpperCamelCase__		(self    :    Any   ,						UpperCamelCase    :    List[int]   ,						UpperCamelCase    :    Optional[List[int]] = None ):

             '''simple docstring'''







             lowercase__      			= token_ids_a + [self.eos_token_id]
             if token_ids_a is None:
                    return self.prefix_tokens + token_ids_a
             else:
                    lowercase__      			= token_ids_a + [self.eos_token_id]
                    return self.prefix_tokens + token_ids_a + token_ids_a



      def       UpperCamelCase__		(self    :    Optional[Any]   ,						UpperCamelCase    :    List[int]   ,						UpperCamelCase    :    Optional[List[int]] = None ):

             '''simple docstring'''







             lowercase__      			= [self.eos_token_id]

             if token_ids_a is None:
                    return len(token_ids_a + eos ) * [0]
             return len(token_ids_a + eos + token_ids_a + eos ) * [0]



      def       UpperCamelCase__		(self    :    List[Any] ):

             '''simple docstring'''







             return list(
                 set(filter(lambda UpperCamelCase : bool(re.search(R'''<extra_id_\d+>'''   ,						UpperCamelCase ) ) is not None   ,						self.additional_special_tokens ) ) )






      def       UpperCamelCase__		(self    :    Union[str, Any] ):

             '''simple docstring'''







             return [self.convert_tokens_to_ids(UpperCamelCase ) for token in self.get_sentinel_tokens()]




