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

_A     :			Tuple  						=			2_56

class 						a__		( a_		):
   __lowerCAmelCase				=							["""melgan"""]
   def __init__(     self      ,       _a      ,       _a      ,       _a      ,       _a      ,       _a      ,       ):
          super().__init__()

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

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

          lowercase						,       lowercase       :							Tuple									=				self.continuous_encoder(
              encoder_inputs=_a      ,       encoder_inputs_mask=_a							)

          return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
   def      __magic_name__     (     self      ,       _a      ,       _a      ,       _a							):
          lowercase       :							int									=				noise_time
          if not torch.is_tensor(_a							):
                 lowercase       :							Union[str, Any]									=				torch.tensor([timesteps]      ,       dtype=torch.long      ,       device=input_tokens.device							)
          elif torch.is_tensor(_a							) and len(timesteps.shape							) == 0:
                 lowercase       :							Optional[Any]									=				timesteps[None].to(input_tokens.device							)

          # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
          lowercase       :							str									=				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 = 100      ,       _a = True      ,       _a = "numpy"      ,       _a = None      ,       _a = 1      ,       ):
          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       :							Dict									=				np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]      ,       dtype=np.floataa							)
          lowercase       :							Dict									=				np.zeros([1, 0, self.n_dims]      ,       np.floataa							)
          lowercase       :							Tuple									=				torch.ones((1, TARGET_FEATURE_LENGTH)      ,       dtype=_a      ,       device=self.device							)

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

                 lowercase       :							List[str]									=				self.scale_features(
                     _a      ,       output_range=[-1.0, 1.0]      ,       clip=_a							)

                 lowercase       :							Optional[int]									=				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       :							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       :							Optional[Any]									=				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       :							Union[str, Any]									=				self.scheduler.step(_a      ,       _a      ,       _a      ,       generator=_a							).prev_sample

                 lowercase       :							Dict									=				self.scale_to_features(_a      ,       input_range=[-1.0, 1.0]							)
                 lowercase       :							List[Any]									=				mel[:1]
                 lowercase       :							Tuple									=				mel.cpu().float().numpy()

                 lowercase       :							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(_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       :							List[Any]									=				self.melgan(input_features=full_pred_mel.astype(np.floataa							)							)
          else:
                 lowercase       :							Dict									=				full_pred_mel

          if not return_dict:
                 return (output,)

          return AudioPipelineOutput(audios=_a							)




"""simple docstring"""




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_A     :			Optional[Any]  						=			{
    """configuration_bridgetower""": [
        """BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """BridgeTowerConfig""",
        """BridgeTowerTextConfig""",
        """BridgeTowerVisionConfig""",
    ],
    """processing_bridgetower""": ["""BridgeTowerProcessor"""],
}

try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A     :			Any  						=			["""BridgeTowerImageProcessor"""]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A     :			List[Any]  						=			[
       """BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """BridgeTowerForContrastiveLearning""",
       """BridgeTowerForImageAndTextRetrieval""",
       """BridgeTowerForMaskedLM""",
       """BridgeTowerModel""",
       """BridgeTowerPreTrainedModel""",
   ]


if TYPE_CHECKING:
   from .configuration_bridgetower import (
       BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP,
       BridgeTowerConfig,
       BridgeTowerTextConfig,
       BridgeTowerVisionConfig,
   )
   from .processing_bridgetower import BridgeTowerProcessor

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .image_processing_bridgetower import BridgeTowerImageProcessor

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_bridgetower import (
          BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST,
          BridgeTowerForContrastiveLearning,
          BridgeTowerForImageAndTextRetrieval,
          BridgeTowerForMaskedLM,
          BridgeTowerModel,
          BridgeTowerPreTrainedModel,
      )


else:
   import sys

   _A     :			Any  						=			_LazyModule(__name__, globals()["""__file__"""], _import_structure)


