





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


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

lowercase__						:			Optional[int]       =				2_56
class 				__lowerCAmelCase     (    a_ ):






       """simple docstring"""
       _snake_case	:     Optional[int]										=    ['melgan']





       def __init__(							self   :		int       , lowerCAmelCase__   :		Optional[Any]       , lowerCAmelCase__   :		int       , lowerCAmelCase__   :		str       , lowerCAmelCase__   :		Union[str, Any]       , lowerCAmelCase__   :		Union[str, Any]       , )    ->     Dict:

            '''simple docstring'''




            super().__init__()

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

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





       def snake_case__						(							self   :		int       , lowerCAmelCase__   :		List[Any]       , lowerCAmelCase__   :		Union[str, Any]=(-1.0, 1.0)       , lowerCAmelCase__   :		Optional[Any]=False     )    ->     Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase    ,				_UpperCamelCase				    =       output_range
            if clip:
                 _UpperCamelCase				    =       torch.clip(_A       , 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 snake_case__						(							self   :		List[Any]       , lowerCAmelCase__   :		Union[str, Any]       , lowerCAmelCase__   :		int=(-1.0, 1.0)       , lowerCAmelCase__   :		str=False     )    ->     Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase    ,				_UpperCamelCase				    =       input_range
            _UpperCamelCase				    =       torch.clip(_A       , _A       , _A     ) 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 snake_case__						(							self   :		int       , lowerCAmelCase__   :		Tuple       , lowerCAmelCase__   :		int       , lowerCAmelCase__   :		List[str]     )    ->     Optional[int]:

            '''simple docstring'''




            _UpperCamelCase				    =       input_tokens > 0
            _UpperCamelCase    ,				_UpperCamelCase				    =       self.notes_encoder(
                encoder_input_tokens=_A       , encoder_inputs_mask=_A     )

            _UpperCamelCase    ,				_UpperCamelCase				    =       self.continuous_encoder(
                encoder_inputs=_A       , encoder_inputs_mask=_A     )

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





       def snake_case__						(							self   :		int       , lowerCAmelCase__   :		Tuple       , lowerCAmelCase__   :		List[Any]       , lowerCAmelCase__   :		Any     )    ->     int:

            '''simple docstring'''




            _UpperCamelCase				    =       noise_time
            if not torch.is_tensor(_A     ):
                 _UpperCamelCase				    =       torch.tensor([timesteps]       , dtype=torch.long       , device=input_tokens.device     )
            elif torch.is_tensor(_A     ) 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=_A       , decoder_input_tokens=_A       , decoder_noise_time=_A     )
            return logits







       @torch.no_grad()
       def __call__(							self   :		str       , lowerCAmelCase__   :		str       , lowerCAmelCase__   :		Union[str, Any] = None       , lowerCAmelCase__   :		Union[str, Any] = 100       , lowerCAmelCase__   :		str = True       , lowerCAmelCase__   :		List[str] = "numpy"       , lowerCAmelCase__   :		List[Any] = None       , lowerCAmelCase__   :		Tuple = 1       , )    ->     str:

            '''simple docstring'''




            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     )}."""     )

            _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=_A       , device=self.device     )

            for i, encoder_input_tokens in enumerate(_A     ):
                 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=_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.
                      _UpperCamelCase				    =       ones

                 _UpperCamelCase				    =       self.scale_features(
                     _A       , output_range=[-1.0, 1.0]       , clip=_A     )

                 _UpperCamelCase				    =       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
                 _UpperCamelCase				    =       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     )     ):
                      _UpperCamelCase				    =       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
                      _UpperCamelCase				    =       self.scheduler.step(_A       , _A       , _A       , generator=_A     ).prev_sample

                 _UpperCamelCase				    =       self.scale_to_features(_A       , 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(_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":
                 _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=_A     )










from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import tensorflow as tf

				from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel

@require_tf
class 	A_       :
	UpperCAmelCase__					=			MBartConfig
	UpperCAmelCase__					=			{}
	UpperCAmelCase__					=			'''gelu'''
	def __init__(    self							,					_A							,					_A=1_3							,					_A=7							,					_A=True							,					_A=False							,					_A=9_9							,					_A=3_2							,					_A=2							,					_A=4							,					_A=3_7							,					_A=0.1							,					_A=0.1							,					_A=2_0							,					_A=2							,					_A=1							,					_A=0							,					):






				'''simple docstring'''







				UpperCAmelCase   		=				parent
				UpperCAmelCase   		=				batch_size
				UpperCAmelCase   		=				seq_length
				UpperCAmelCase   		=				is_training
				UpperCAmelCase   		=				use_labels
				UpperCAmelCase   		=				vocab_size
				UpperCAmelCase   		=				hidden_size
				UpperCAmelCase   		=				num_hidden_layers
				UpperCAmelCase   		=				num_attention_heads
				UpperCAmelCase   		=				intermediate_size
				UpperCAmelCase   		=				hidden_dropout_prob
				UpperCAmelCase   		=				attention_probs_dropout_prob
				UpperCAmelCase   		=				max_position_embeddings
				UpperCAmelCase   		=				eos_token_id
				UpperCAmelCase   		=				pad_token_id
				UpperCAmelCase   		=				bos_token_id
	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				ids_tensor([self.batch_size, self.seq_length - 1]							,					self.vocab_size		)
				UpperCAmelCase   		=				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size		)							,					1		)
				UpperCAmelCase   		=				tf.concat([input_ids, eos_tensor]							,					axis=1		)

				UpperCAmelCase   		=				ids_tensor([self.batch_size, self.seq_length]							,					self.vocab_size		)

				UpperCAmelCase   		=				self.config_cls(
				    vocab_size=self.vocab_size							,					d_model=self.hidden_size							,					encoder_layers=self.num_hidden_layers							,					decoder_layers=self.num_hidden_layers							,					encoder_attention_heads=self.num_attention_heads							,					decoder_attention_heads=self.num_attention_heads							,					encoder_ffn_dim=self.intermediate_size							,					decoder_ffn_dim=self.intermediate_size							,					dropout=self.hidden_dropout_prob							,					attention_dropout=self.attention_probs_dropout_prob							,					max_position_embeddings=self.max_position_embeddings							,					eos_token_ids=[2]							,					bos_token_id=self.bos_token_id							,					pad_token_id=self.pad_token_id							,					decoder_start_token_id=self.pad_token_id							,					**self.config_updates							,					)
				UpperCAmelCase   		=				prepare_mbart_inputs_dict(_A							,					_A							,					_A		)
				return config, inputs_dict







	def      _lowercase				(    self							,					_A							,					_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				TFMBartModel(config=_A		).get_decoder()
				UpperCAmelCase   		=				inputs_dict['''input_ids''']

				UpperCAmelCase   		=				input_ids[:1, :]
				UpperCAmelCase   		=				inputs_dict['''attention_mask'''][:1, :]
				UpperCAmelCase   		=				inputs_dict['''head_mask''']
				UpperCAmelCase   		=				1

				# first forward pass
				UpperCAmelCase   		=				model(_A							,					attention_mask=_A							,					head_mask=_A							,					use_cache=_A		)

				UpperCAmelCase		,			UpperCAmelCase   		=				outputs.to_tuple()
				UpperCAmelCase   		=				past_key_values[1]





def 						__SCREAMING_SNAKE_CASE  (				UpperCamelCase__			,			UpperCamelCase__			,			UpperCamelCase__			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			)  ->				List[str]:







			'''simple docstring'''

			if attention_mask is None:
						UpperCAmelCase   		=				tf.cast(tf.math.not_equal(UpperCamelCase__			,			config.pad_token_id )			,			tf.inta )
			if decoder_attention_mask is None:
						UpperCAmelCase   		=				tf.concat(
						    [
						        tf.ones(decoder_input_ids[:, :1].shape			,			dtype=tf.inta ),
						        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]			,			config.pad_token_id )			,			tf.inta ),
						    ]			,			axis=-1			,			)
			if head_mask is None:
						UpperCAmelCase   		=				tf.ones((config.encoder_layers, config.encoder_attention_heads) )
			if decoder_head_mask is None:
						UpperCAmelCase   		=				tf.ones((config.decoder_layers, config.decoder_attention_heads) )
			if cross_attn_head_mask is None:
						UpperCAmelCase   		=				tf.ones((config.decoder_layers, config.decoder_attention_heads) )
			return {
			    "input_ids": input_ids,
			    "decoder_input_ids": decoder_input_ids,
			    "attention_mask": attention_mask,
			    "decoder_attention_mask": decoder_attention_mask,
			    "head_mask": head_mask,
			    "decoder_head_mask": decoder_head_mask,
			    "cross_attn_head_mask": cross_attn_head_mask,
			}

@require_tf
class 	A_       (a_     ,							a_     ,							unittest.TestCase			):
	UpperCAmelCase__					=			(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
	UpperCAmelCase__					=			(TFMBartForConditionalGeneration,) if is_tf_available() else ()
	UpperCAmelCase__					=			(
	    {
	        '''conversational''': TFMBartForConditionalGeneration,
	        '''feature-extraction''': TFMBartModel,
	        '''summarization''': TFMBartForConditionalGeneration,
	        '''text2text-generation''': TFMBartForConditionalGeneration,
	        '''translation''': TFMBartForConditionalGeneration,
	    }
	    if is_tf_available()
	    else {}
	)
	UpperCAmelCase__					=			True
	UpperCAmelCase__					=			False
	UpperCAmelCase__					=			False
	def      _lowercase				(    self							,					_A							,					_A							,					_A							,					_A							,					_A		):






				'''simple docstring'''







				if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
							# Exception encountered when calling layer '...'
							return True

				return False
	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				TFMBartModelTester(self		)
				UpperCAmelCase   		=				ConfigTester(self							,					config_class=_A		)
	def      _lowercase				(    self		):






				'''simple docstring'''







				self.config_tester.run_common_tests()







	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.model_tester.prepare_config_and_inputs_for_common()
				self.model_tester.check_decoder_model_past_large_inputs(*_A		)

@require_sentencepiece
@require_tokenizers
@require_tf
class 	A_       (unittest.TestCase			):
	UpperCAmelCase__					=			[
	    ''' UN Chief Says There Is No Military Solution in Syria''',
	]
	UpperCAmelCase__					=			[
	    '''Şeful ONU declară că nu există o soluţie militară în Siria''',
	]
	UpperCAmelCase__					=			'''facebook/mbart-large-en-ro'''
	@cached_property
	def      _lowercase				(    self		):






				'''simple docstring'''







				return AutoTokenizer.from_pretrained(self.model_name		)
	@cached_property
	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name		)
				return model
	def      _lowercase				(    self							,					**_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.translate_src_text(**_A		)
				self.assertListEqual(self.expected_text							,					_A		)
	def      _lowercase				(    self							,					**_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.tokenizer(self.src_text							,					**_A							,					return_tensors='''tf'''		)
				UpperCAmelCase   		=				self.model.generate(
				    model_inputs.input_ids							,					attention_mask=model_inputs.attention_mask							,					num_beams=2		)
				UpperCAmelCase   		=				self.tokenizer.batch_decode(_A							,					skip_special_tokens=_A		)
				return generated_words







	@slow
	def      _lowercase				(    self		):






				'''simple docstring'''







				self._assert_generated_batch_equal_expected()



