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

lowerCamelCase__        =		256




class 			A__	(     __lowerCamelCase):
		A_						:	Union[str, Any]           =     ['melgan']

		def __init__(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		):
			super().__init__()

			# From MELGAN
			__lowerCAmelCase      :						Union[str, Any]						      =				math.log(1E-5			)  # Matches MelGAN training.
			__lowerCAmelCase      :						Any						      =				4.0  # Largest value for most examples
			__lowerCAmelCase      :						Optional[int]						      =				1_28

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

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

			__lowerCAmelCase      ,       __lowerCAmelCase      :						int						      =				self.continuous_encoder(
			    encoder_inputs=UpperCamelCase_	,		encoder_inputs_mask=UpperCamelCase_			)

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

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Union[str, Any]						      =				noise_time
			if not torch.is_tensor(UpperCamelCase_			):
				__lowerCAmelCase      :						Optional[int]						      =				torch.tensor([timesteps]	,		dtype=torch.long	,		device=input_tokens.device			)
			elif torch.is_tensor(UpperCamelCase_			) and len(timesteps.shape			) == 0:
				__lowerCAmelCase      :						Dict						      =				timesteps[None].to(input_tokens.device			)

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

			__lowerCAmelCase      :						Optional[Any]						      =				self.decoder(
			    encodings_and_masks=UpperCamelCase_	,		decoder_input_tokens=UpperCamelCase_	,		decoder_noise_time=UpperCamelCase_			)
			return logits







		@torch.no_grad()
		def __call__(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE = None	,		_SCREAMING_SNAKE_CASE = 1_00	,		_SCREAMING_SNAKE_CASE = True	,		_SCREAMING_SNAKE_CASE = "numpy"	,		_SCREAMING_SNAKE_CASE = None	,		_SCREAMING_SNAKE_CASE = 1	,		):
			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_			)}."			)

			__lowerCAmelCase      :						List[Any]						      =				np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]	,		dtype=np.floataa			)
			__lowerCAmelCase      :						Any						      =				np.zeros([1, 0, self.n_dims]	,		np.floataa			)
			__lowerCAmelCase      :						str						      =				torch.ones((1, TARGET_FEATURE_LENGTH)	,		dtype=UpperCamelCase_	,		device=self.device			)

			for i, encoder_input_tokens in enumerate(UpperCamelCase_			):
				if i == 0:
					__lowerCAmelCase      :						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.
					__lowerCAmelCase      :						Optional[int]						      =				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.
					__lowerCAmelCase      :						Any						      =				ones

				__lowerCAmelCase      :						int						      =				self.scale_features(
				    UpperCamelCase_	,		output_range=[-1.0, 1.0]	,		clip=UpperCamelCase_			)

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

				__lowerCAmelCase      :						Tuple						      =				self.scale_to_features(UpperCamelCase_	,		input_range=[-1.0, 1.0]			)
				__lowerCAmelCase      :						Optional[int]						      =				mel[:1]
				__lowerCAmelCase      :						Tuple						      =				mel.cpu().float().numpy()

				__lowerCAmelCase      :						int						      =				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":
				__lowerCAmelCase      :						List[str]						      =				self.melgan(input_features=full_pred_mel.astype(np.floataa			)			)
			else:
				__lowerCAmelCase      :						Dict						      =				full_pred_mel

			if not return_dict:
				return (output,)

			return AudioPipelineOutput(audios=UpperCamelCase_			)



"""simple docstring"""







import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import ClassLabel, Features, Value
from .base import TaskTemplate




@dataclass(frozen=_lowerCamelCase)
class 			A__	(     _lowerCamelCase):
		# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
		A_						:	str           =     field(default='text-classification'	,					metadata={'include_in_asdict_even_if_is_default': True})
		A_						:	ClassVar[Features]           =     Features({'text': Value('string')})
		A_						:	ClassVar[Features]           =     Features({'labels': ClassLabel})
		A_						:	str           =     "text"
		A_						:	str           =     "labels"

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE			):
			if self.label_column not in features:
				raise ValueError(f"Column {self.label_column} is not present in features."			)
			if not isinstance(features[self.label_column]	,		_SCREAMING_SNAKE_CASE			):
				raise ValueError(f"Column {self.label_column} is not a ClassLabel."			)
			__lowerCAmelCase      :						Any						      =				copy.deepcopy(self			)
			__lowerCAmelCase      :						Dict						      =				self.label_schema.copy()
			__lowerCAmelCase      :						List[Any]						      =				features[self.label_column]
			__lowerCAmelCase      :						Dict						      =				label_schema
			return task_template







		@property
		def 							__lowerCamelCase							(				self			):
			return {
			    self.text_column: "text",
			    self.label_column: "labels",
			}