






import itertools
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa

import datasets
from datasets.table import table_cast


a_ :    Optional[Any]							=      datasets.utils.logging.get_logger(__name__)


@dataclass
class        lowercase__       (     datasets.BuilderConfig		):
	a_             =None





class        lowercase__       (     datasets.ArrowBasedBuilder		):
	a_             =ArrowConfig

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







							'''simple docstring'''





							return datasets.DatasetInfo(features=self.config.features    )

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase    )->   Union[str, Any]:







							'''simple docstring'''





							if not self.config.data_files:
													raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}"    )
							lowerCAmelCase__	 =  dl_manager.download_and_extract(self.config.data_files    )
							if isinstance(__UpperCAmelCase						,      (str, list, tuple)    ):
													lowerCAmelCase__	 =  data_files
													if isinstance(__UpperCAmelCase						,      __UpperCAmelCase    ):
																			lowerCAmelCase__	 =  [files]
													# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
													lowerCAmelCase__	 =  [dl_manager.iter_files(__UpperCAmelCase    ) for file in files]
													return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,      gen_kwargs={"files": files}    )]
							lowerCAmelCase__	 =  []
							for split_name, files in data_files.items():
													if isinstance(__UpperCAmelCase						,      __UpperCAmelCase    ):
																			lowerCAmelCase__	 =  [files]
													# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
													lowerCAmelCase__	 =  [dl_manager.iter_files(__UpperCAmelCase    ) for file in files]
													# Infer features is they are stoed in the arrow schema
													if self.info.features is None:
																			for file in itertools.chain.from_iterable(__UpperCAmelCase    ):
																									with open(__UpperCAmelCase						,      "rb"    ) as f:
																															lowerCAmelCase__	 =  datasets.Features.from_arrow_schema(pa.ipc.open_stream(__UpperCAmelCase    ).schema    )
																									break
													splits.append(datasets.SplitGenerator(name=__UpperCAmelCase						,      gen_kwargs={"files": files}    )    )
							return splits

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase    )->   pa.Table:







							'''simple docstring'''





							if self.info.features is not None:
													# more expensive cast to support nested features with keys in a different order
													# allows str <-> int/float or str to Audio for example
													lowerCAmelCase__	 =  table_cast(__UpperCAmelCase						,      self.info.features.arrow_schema    )
							return pa_table


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







							'''simple docstring'''





							for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase    )    ):
													with open(__UpperCAmelCase						,      "rb"    ) as f:
																			try:
																									for batch_idx, record_batch in enumerate(pa.ipc.open_stream(__UpperCAmelCase    )    ):
																															lowerCAmelCase__	 =  pa.Table.from_batches([record_batch]    )
																															# Uncomment for debugging (will print the Arrow table size and elements)
																															# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																															# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																															yield F"{file_idx}_{batch_idx}", self._cast_table(__UpperCAmelCase    )
																			except ValueError as e:
																									logger.error(F"Failed to read file '{file}' with error {type(__UpperCAmelCase    )}: {e}"    )
																									raise














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






