






import random
import shutil
import tempfile
import unittest

import numpy as np

from transformers import TaTokenizer, TaTokenizerFast
from transformers.testing_utils import require_sentencepiece, require_torch
from transformers.utils.import_utils import is_speech_available, is_torch_available


if is_torch_available():
	pass

if is_speech_available():
	from transformers import EncodecFeatureExtractor, MusicgenProcessor


a_ :    str							=      random.Random()


def     _a					(       UpperCamelCase_   :			Tuple      ,				UpperCamelCase_   :			str=1.0      ,				UpperCamelCase_   :			Dict=None      ,				UpperCamelCase_   :			Dict=None				)	->				Any:
						"""simple docstring"""







						if rng is None:
												lowerCAmelCase__	 =  global_rng

						lowerCAmelCase__	 =  []
						for batch_idx in range(shape[0]				):
												values.append([]				)
												for _ in range(shape[1]				):
																		values[-1].append(rng.random() * scale				)

						return values





@require_torch
@require_sentencepiece
class        lowercase__       (     unittest.TestCase		):

	def 						UpperCAmelCase					(							self    )->   str:







							'''simple docstring'''





							lowerCAmelCase__	 =  "facebook/musicgen-small"
							lowerCAmelCase__	 =  tempfile.mkdtemp()

	def 						UpperCAmelCase					(							self						,      **__UpperCAmelCase    )->   str:







							'''simple docstring'''





							return TaTokenizer.from_pretrained(self.checkpoint						,      **lowerCAmelCase__    )

	def 						UpperCAmelCase					(							self						,      **__UpperCAmelCase    )->   str:







							'''simple docstring'''





							return EncodecFeatureExtractor.from_pretrained(self.checkpoint						,      **lowerCAmelCase__    )

	def 						UpperCAmelCase					(							self    )->   str:







							'''simple docstring'''





							shutil.rmtree(self.tmpdirname    )

	def 						UpperCAmelCase					(							self    )->   List[str]:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.get_tokenizer()
							lowerCAmelCase__	 =  self.get_feature_extractor()

							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=lowerCAmelCase__						,      feature_extractor=lowerCAmelCase__    )

							processor.save_pretrained(self.tmpdirname    )
							lowerCAmelCase__	 =  MusicgenProcessor.from_pretrained(self.tmpdirname    )

							self.assertEqual(processor.tokenizer.get_vocab()						,      tokenizer.get_vocab()    )
							self.assertIsInstance(processor.tokenizer						,      lowerCAmelCase__    )

							self.assertEqual(processor.feature_extractor.to_json_string()						,      feature_extractor.to_json_string()    )
							self.assertIsInstance(processor.feature_extractor						,      lowerCAmelCase__    )

	def 						UpperCAmelCase					(							self    )->   List[str]:







							'''simple docstring'''





							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=self.get_tokenizer()						,      feature_extractor=self.get_feature_extractor()    )
							processor.save_pretrained(self.tmpdirname    )

							lowerCAmelCase__	 =  self.get_tokenizer(bos_token="(BOS)"						,      eos_token="(EOS)"    )
							lowerCAmelCase__	 =  self.get_feature_extractor(do_normalize=lowerCAmelCase__						,      padding_value=1.0    )

							lowerCAmelCase__	 =  MusicgenProcessor.from_pretrained(
							    self.tmpdirname						,      bos_token="(BOS)"						,      eos_token="(EOS)"						,      do_normalize=lowerCAmelCase__						,      padding_value=1.0    )

							self.assertEqual(processor.tokenizer.get_vocab()						,      tokenizer_add_kwargs.get_vocab()    )
							self.assertIsInstance(processor.tokenizer						,      lowerCAmelCase__    )

							self.assertEqual(processor.feature_extractor.to_json_string()						,      feature_extractor_add_kwargs.to_json_string()    )
							self.assertIsInstance(processor.feature_extractor						,      lowerCAmelCase__    )

	def 						UpperCAmelCase					(							self    )->   Any:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.get_feature_extractor()
							lowerCAmelCase__	 =  self.get_tokenizer()

							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=lowerCAmelCase__						,      feature_extractor=lowerCAmelCase__    )

							lowerCAmelCase__	 =  floats_list((3, 1000)    )

							lowerCAmelCase__	 =  feature_extractor(lowerCAmelCase__						,      return_tensors="np"    )
							lowerCAmelCase__	 =  processor(lowerCAmelCase__						,      return_tensors="np"    )

							for key in input_feat_extract.keys():
													self.assertAlmostEqual(input_feat_extract[key].sum()						,      input_processor[key].sum()						,      delta=1E-2    )

	def 						UpperCAmelCase					(							self    )->   List[str]:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.get_feature_extractor()
							lowerCAmelCase__	 =  self.get_tokenizer()

							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=lowerCAmelCase__						,      feature_extractor=lowerCAmelCase__    )

							lowerCAmelCase__	 =  "This is a test string"

							lowerCAmelCase__	 =  processor(text=lowerCAmelCase__    )

							lowerCAmelCase__	 =  tokenizer(lowerCAmelCase__    )

							for key in encoded_tok.keys():
													self.assertListEqual(encoded_tok[key]						,      encoded_processor[key]    )

	def 						UpperCAmelCase					(							self    )->   List[str]:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.get_feature_extractor()
							lowerCAmelCase__	 =  self.get_tokenizer()

							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=lowerCAmelCase__						,      feature_extractor=lowerCAmelCase__    )

							lowerCAmelCase__	 =  [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

							lowerCAmelCase__	 =  processor.batch_decode(sequences=lowerCAmelCase__    )
							lowerCAmelCase__	 =  tokenizer.batch_decode(lowerCAmelCase__    )

							self.assertListEqual(lowerCAmelCase__						,      lowerCAmelCase__    )

	def 						UpperCAmelCase					(							self    )->   Tuple:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.get_feature_extractor()
							lowerCAmelCase__	 =  self.get_tokenizer()

							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=lowerCAmelCase__						,      feature_extractor=lowerCAmelCase__    )

							self.assertListEqual(
							    processor.model_input_names						,      feature_extractor.model_input_names						,      msg="`processor` and `feature_extractor` model input names do not match"						,      )


	def 						UpperCAmelCase					(							self    )->   List[Any]:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.get_feature_extractor(padding_side="left"    )
							lowerCAmelCase__	 =  self.get_tokenizer()

							lowerCAmelCase__	 =  MusicgenProcessor(tokenizer=lowerCAmelCase__						,      feature_extractor=lowerCAmelCase__    )

							lowerCAmelCase__	 =  [floats_list((1, x)    )[0] for x in range(5						,      20						,      5    )]
							lowerCAmelCase__	 =  processor(lowerCAmelCase__    ).padding_mask

							lowerCAmelCase__	 =  np.asarray(floats_list((3, 20)    )    )[:, None, :]
							lowerCAmelCase__	 =  processor.batch_decode(lowerCAmelCase__						,      padding_mask=lowerCAmelCase__    )

							self.assertIsInstance(lowerCAmelCase__						,      lowerCAmelCase__    )

							for audio in decoded_audios:
													self.assertIsInstance(lowerCAmelCase__						,      np.ndarray    )

							self.assertTrue(decoded_audios[0].shape == (1, 10)    )
							self.assertTrue(decoded_audios[1].shape == (1, 15)    )
							self.assertTrue(decoded_audios[2].shape == (1, 20)    )














import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


a_							=      logging.get_logger(__name__)

a_							=      {
    '''facebook/musicgen-small''': '''https://huggingface.co/facebook/musicgen-small/resolve/main/config.json''',
    # See all Musicgen models at https://huggingface.co/models?filter=musicgen
}


class        lowercase__       (     _UpperCAmelCase		):
	a_             ="""musicgen_decoder"""
	a_             =["""past_key_values"""]

	def __init__(							self						,      __UpperCAmelCase=2048						,      __UpperCAmelCase=2048						,      __UpperCAmelCase=24						,      __UpperCAmelCase=4096						,      __UpperCAmelCase=16						,      __UpperCAmelCase=0.0						,      __UpperCAmelCase=True						,      __UpperCAmelCase="gelu"						,      __UpperCAmelCase=1024						,      __UpperCAmelCase=0.1						,      __UpperCAmelCase=0.0						,      __UpperCAmelCase=0.0						,      __UpperCAmelCase=0.02						,      __UpperCAmelCase=False						,      __UpperCAmelCase=4						,      __UpperCAmelCase=2048						,      __UpperCAmelCase=2048						,      __UpperCAmelCase=None						,      __UpperCAmelCase=False						,      **__UpperCAmelCase						,      )->   Optional[Any]:







							'''simple docstring'''





							lowerCAmelCase__	 =  vocab_size
							lowerCAmelCase__	 =  max_position_embeddings
							lowerCAmelCase__	 =  hidden_size
							lowerCAmelCase__	 =  ffn_dim
							lowerCAmelCase__	 =  num_hidden_layers
							lowerCAmelCase__	 =  num_attention_heads
							lowerCAmelCase__	 =  dropout
							lowerCAmelCase__	 =  attention_dropout
							lowerCAmelCase__	 =  activation_dropout
							lowerCAmelCase__	 =  activation_function
							lowerCAmelCase__	 =  initializer_factor
							lowerCAmelCase__	 =  layerdrop
							lowerCAmelCase__	 =  use_cache
							lowerCAmelCase__	 =  scale_embedding  # scale factor will be sqrt(d_model) if True
							lowerCAmelCase__	 =  num_codebooks
							super().__init__(
							    pad_token_id=__UpperCAmelCase						,      bos_token_id=__UpperCAmelCase						,      eos_token_id=__UpperCAmelCase						,      tie_word_embeddings=__UpperCAmelCase						,      **__UpperCAmelCase						,      )





class        lowercase__       (     _UpperCAmelCase		):
	a_             ="""musicgen"""
	a_             =True

	def __init__(							self						,      **__UpperCAmelCase    )->   Any:







							'''simple docstring'''





							super().__init__(**__UpperCAmelCase    )
							if "text_encoder" not in kwargs or "audio_encoder" not in kwargs or "decoder" not in kwargs:
													raise ValueError("Config has to be initialized with text_encoder, audio_encoder and decoder config"    )

							lowerCAmelCase__	 =  kwargs.pop("text_encoder"    )
							lowerCAmelCase__	 =  text_encoder_config.pop("model_type"    )

							lowerCAmelCase__	 =  kwargs.pop("audio_encoder"    )
							lowerCAmelCase__	 =  audio_encoder_config.pop("model_type"    )

							lowerCAmelCase__	 =  kwargs.pop("decoder"    )

							lowerCAmelCase__	 =  AutoConfig.for_model(__UpperCAmelCase						,      **__UpperCAmelCase    )
							lowerCAmelCase__	 =  AutoConfig.for_model(__UpperCAmelCase						,      **__UpperCAmelCase    )
							lowerCAmelCase__	 =  MusicgenDecoderConfig(**__UpperCAmelCase    )
							lowerCAmelCase__	 =  True

	@classmethod
	def 						UpperCAmelCase					(							cls						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      **__UpperCAmelCase						,      )->   Tuple:







							'''simple docstring'''





							return cls(
							    text_encoder=text_encoder_config.to_dict()						,      audio_encoder=audio_encoder_config.to_dict()						,      decoder=decoder_config.to_dict()						,      **__UpperCAmelCase						,      )


	def 						UpperCAmelCase					(							self    )->   Optional[int]:







							'''simple docstring'''





							lowerCAmelCase__	 =  copy.deepcopy(self.__dict__    )
							lowerCAmelCase__	 =  self.text_encoder.to_dict()
							lowerCAmelCase__	 =  self.audio_encoder.to_dict()
							lowerCAmelCase__	 =  self.decoder.to_dict()
							lowerCAmelCase__	 =  self.__class__.model_type
							return output






