"""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  :		Any           =       logging.get_logger(__name__)  # pylint: disable=invalid-name

_UpperCamelCase  :		Tuple           =       2_56


class 	UpperCAmelCase_      (       A_):
      lowerCamelCase__						:       List[str]					    =    ["melgan"]


      def __init__(  self						,     a						,     a						,     a						,     a						,     a						,     )			->   None:
             super().__init__()

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

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


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

             lowercase__     :						Tuple         =      self.continuous_encoder(
                 encoder_inputs=a						,     encoder_inputs_mask=a				)

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


      def 						_UpperCAmelCase			(  self						,     a						,     a						,     a				)			->   Union[str, Any]:
             lowercase__     :						Optional[int]         =      noise_time
             if not torch.is_tensor(a				):
                    lowercase__     :						int         =      torch.tensor([timesteps]						,     dtype=torch.long						,     device=input_tokens.device				)
             elif torch.is_tensor(a				) and len(timesteps.shape				) == 0:
                    lowercase__     :						Tuple         =      timesteps[None].to(input_tokens.device				)

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

             lowercase__     :						List[str]         =      self.decoder(
                 encodings_and_masks=a						,     decoder_input_tokens=a						,     decoder_noise_time=a				)
             return logits


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

             lowercase__     :						Optional[Any]         =      np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]						,     dtype=np.floataa				)
             lowercase__     :						Dict         =      np.zeros([1, 0, self.n_dims]						,     np.floataa				)
             lowercase__     :						List[Any]         =      torch.ones((1, TARGET_FEATURE_LENGTH)						,     dtype=a						,     device=self.device				)

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

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

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

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

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

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

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

                    lowercase__     :						Any         =      self.scale_to_features(a						,     input_range=[-1.0, 1.0]				)
                    lowercase__     :						int         =      mel[:1]
                    lowercase__     :						Optional[int]         =      mel.cpu().float().numpy()

                    lowercase__     :						str         =      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(a						,     a				)

                    logger.info('Generated segment'						,     a				)

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

             if not return_dict:
                    return (output,)

             return AudioPipelineOutput(audios=a				)





"""simple docstring"""
from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


UpperCAmelCase				=						"""\
@misc{wu2016googles,
      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""

UpperCAmelCase				=						"""\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

UpperCAmelCase				=						"""\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION				)
class 	lowercase__				(					datasets.Metric				):





   def 		UpperCamelCase_  (							self)  ->  MetricInfo:
      return datasets.MetricInfo(
          description=_DESCRIPTION      ,   citation=_CITATION      ,   inputs_description=_KWARGS_DESCRIPTION      ,   features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""string"""      ,   id="""token""")      ,   id="""sequence"""),
                  """references""": datasets.Sequence(
                      datasets.Sequence(datasets.Value("""string"""      ,   id="""token""")      ,   id="""sequence""")      ,   id="""references"""),
              })      ,   )





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE = 1      ,   SCREAMING_SNAKE_CASE = 4      ,   )  ->  Dict[str, float]:
      return {
          "google_bleu": gleu_score.corpus_gleu(
              list_of_references=SCREAMING_SNAKE_CASE      ,   hypotheses=SCREAMING_SNAKE_CASE      ,   min_len=SCREAMING_SNAKE_CASE      ,   max_len=SCREAMING_SNAKE_CASE)
      }

