




'''simple docstring'''
import copy
import os
from typing import Dict, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings, logging
from ..auto import AutoConfig


A							:				Dict			     =	logging.get_logger(__name__)


A							:				List[Any]			     =	{
    "suno/bark-small": "https://huggingface.co/suno/bark-small/resolve/main/config.json",
    "suno/bark": "https://huggingface.co/suno/bark/resolve/main/config.json",
}

A							:				Dict			     =	"\n    This is the configuration class to store the configuration of a [`{model}`]. It is used to instantiate the model\n    according to the specified arguments, defining the model architecture. Instantiating a configuration with the\n    defaults will yield a similar configuration to that of the Bark [suno/bark](https://huggingface.co/suno/bark)\n    architecture.\n\n    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the\n    documentation from [`PretrainedConfig`] for more information.\n\n    Args:\n        block_size (`int`, *optional*, defaults to 1024):\n            The maximum sequence length that this model might ever be used with. Typically set this to something large\n            just in case (e.g., 512 or 1024 or 2048).\n        input_vocab_size (`int`, *optional*, defaults to 10_048):\n            Vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented by the\n            `inputs_ids` passed when calling [`{model}`]. Defaults to 10_048 but should be carefully thought with\n            regards to the chosen sub-model.\n        output_vocab_size (`int`, *optional*, defaults to 10_048):\n            Output vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented\n            by the: `output_ids` when passing forward a [`{model}`]. Defaults to 10_048 but should be carefully thought\n            with regards to the chosen sub-model.\n        num_layers (`int`, *optional*, defaults to 12):\n            Number of hidden layers in the given sub-model.\n        num_heads (`int`, *optional*, defaults to 12):\n            Number of attention heads for each attention layer in the Transformer architecture.\n        hidden_size (`int`, *optional*, defaults to 768):\n            Dimensionality of the \"intermediate\" (often named feed-forward) layer in the architecture.\n        dropout (`float`, *optional*, defaults to 0.0):\n            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.\n        bias (`bool`, *optional*, defaults to `True`):\n            Whether or not to use bias in the linear layers and layer norm layers.\n        initializer_range (`float`, *optional*, defaults to 0.02):\n            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.\n        use_cache (`bool`, *optional*, defaults to `True`):\n            Whether or not the model should return the last key/values attentions (not used by all models).\n"






class 	SCREAMING_SNAKE_CASE(    UpperCAmelCase__					):
       snake_case_			:					Tuple   = """bark_module"""
       snake_case_			:					Optional[Any]   = ["""past_key_values"""]

       snake_case_			:					Dict   = {
           """num_attention_heads""": """num_heads""",
           """num_hidden_layers""": """num_layers""",
           """vocab_size""": """input_vocab_size""",
           """window_size""": """block_size""",
       }

       def __init__(   self ,		lowerCamelCase__=1024 ,		lowerCamelCase__=1_0048 ,		lowerCamelCase__=1_0048 ,		lowerCamelCase__=12 ,		lowerCamelCase__=12 ,		lowerCamelCase__=768 ,		lowerCamelCase__=0.0 ,		lowerCamelCase__=True ,		lowerCamelCase__=0.02 ,		lowerCamelCase__=True ,		**lowerCamelCase__ ,		)   -> Optional[Any]:

           """simple docstring"""



           __lowercase      =						block_size
           __lowercase      =						input_vocab_size
           __lowercase      =						output_vocab_size
           __lowercase      =						num_layers
           __lowercase      =						num_heads
           __lowercase      =						hidden_size
           __lowercase      =						dropout
           __lowercase      =						bias
           __lowercase      =						use_cache
           __lowercase      =						initializer_range

           super().__init__(**__lowercase					)




       @classmethod
       def    snake_case__      (   cls ,		lowerCamelCase__ ,		lowerCamelCase__ = None ,		lowerCamelCase__ = False ,		lowerCamelCase__ = False ,		lowerCamelCase__ = None ,		lowerCamelCase__ = "main" ,		**lowerCamelCase__ ,		)   -> Optional[int]:

           """simple docstring"""



           __lowercase      =						cache_dir
           __lowercase      =						force_download
           __lowercase      =						local_files_only
           __lowercase      =						revision

           cls._set_token_in_kwargs(__lowercase ,		__lowercase					)

           __lowercase,__lowercase      =						cls.get_config_dict(__lowercase ,		**__lowercase					)

           # get the config dict if we are loading from Bark
           if config_dict.get("""model_type"""					) == "bark":
               __lowercase      =						config_dict[F'{cls.model_type}_config']

           if "model_type" in config_dict and hasattr(cls ,		"""model_type"""					) and config_dict["model_type"] != cls.model_type:
               logger.warning(
                   F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                   F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'					)

           return cls.from_dict(__lowercase ,		**__lowercase					)






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="""BarkSemanticConfig"""       ,				model="""BarkSemanticModel"""					)       ,				"""
    Example:

    ```python
    >>> from transformers import BarkSemanticConfig, BarkSemanticModel

    >>> # Initializing a Bark sub-module style configuration
    >>> configuration = BarkSemanticConfig()

    >>> # Initializing a model (with random weights) from the suno/bark style configuration
    >>> model = BarkSemanticModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""       ,				)
class 	SCREAMING_SNAKE_CASE(    UpperCAmelCase__					):
       snake_case_			:					str   = """semantic"""






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="""BarkCoarseConfig"""       ,				model="""BarkCoarseModel"""					)       ,				"""
    Example:

    ```python
    >>> from transformers import BarkCoarseConfig, BarkCoarseModel

    >>> # Initializing a Bark sub-module style configuration
    >>> configuration = BarkCoarseConfig()

    >>> # Initializing a model (with random weights) from the suno/bark style configuration
    >>> model = BarkCoarseModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""       ,				)
class 	SCREAMING_SNAKE_CASE(    UpperCAmelCase__					):
       snake_case_			:					List[str]   = """coarse_acoustics"""






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="""BarkFineConfig"""       ,				model="""BarkFineModel"""					)       ,				"""
        n_codes_total (`int`, *optional*, defaults to 8):
            The total number of audio codebooks predicted. Used in the fine acoustics sub-model.
        n_codes_given (`int`, *optional*, defaults to 1):
            The number of audio codebooks predicted in the coarse acoustics sub-model. Used in the acoustics
            sub-models.
    Example:

    ```python
    >>> from transformers import BarkFineConfig, BarkFineModel

    >>> # Initializing a Bark sub-module style configuration
    >>> configuration = BarkFineConfig()

    >>> # Initializing a model (with random weights) from the suno/bark style configuration
    >>> model = BarkFineModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""       ,				)
class 	SCREAMING_SNAKE_CASE(    UpperCAmelCase__					):
       snake_case_			:					Any   = """fine_acoustics"""

       def __init__(   self ,		lowerCamelCase__=True ,		lowerCamelCase__=8 ,		lowerCamelCase__=1 ,		**lowerCamelCase__					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase      =						n_codes_total
           __lowercase      =						n_codes_given

           super().__init__(tie_word_embeddings=__lowercase ,		**__lowercase					)






class 	SCREAMING_SNAKE_CASE(    UpperCAmelCase__					):
       snake_case_			:					List[str]   = """bark"""
       snake_case_			:					Any   = True

       def __init__(   self ,		lowerCamelCase__ = None ,		lowerCamelCase__ = None ,		lowerCamelCase__ = None ,		lowerCamelCase__ = None ,		lowerCamelCase__=0.02 ,		**lowerCamelCase__ ,		)   -> Dict:

           """simple docstring"""



           if semantic_config is None:
               __lowercase      =						{}
               logger.info("""semantic_config is None. initializing the semantic model with default values."""					)

           if coarse_acoustics_config is None:
               __lowercase      =						{}
               logger.info("""coarse_acoustics_config is None. initializing the coarse model with default values."""					)

           if fine_acoustics_config is None:
               __lowercase      =						{}
               logger.info("""fine_acoustics_config is None. initializing the fine model with default values."""					)

           if codec_config is None:
               __lowercase      =						{}
               logger.info("""codec_config is None. initializing the codec model with default values."""					)

           __lowercase      =						BarkSemanticConfig(**__lowercase					)
           __lowercase      =						BarkCoarseConfig(**__lowercase					)
           __lowercase      =						BarkFineConfig(**__lowercase					)
           __lowercase      =						AutoConfig.for_model(**__lowercase					)

           __lowercase      =						initializer_range

           super().__init__(**__lowercase					)

       @classmethod
       def    snake_case__      (   cls ,		lowerCamelCase__ ,		lowerCamelCase__ ,		lowerCamelCase__ ,		lowerCamelCase__ ,		**lowerCamelCase__ ,		)   -> Any:

           """simple docstring"""



           return cls(
               semantic_config=semantic_config.to_dict() ,		coarse_acoustics_config=coarse_acoustics_config.to_dict() ,		fine_acoustics_config=fine_acoustics_config.to_dict() ,		codec_config=codec_config.to_dict() ,		**__lowercase ,		)




       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase      =						copy.deepcopy(self.__dict__					)

           __lowercase      =						self.semantic_config.to_dict()
           __lowercase      =						self.coarse_acoustics_config.to_dict()
           __lowercase      =						self.fine_acoustics_config.to_dict()
           __lowercase      =						self.codec_config.to_dict()

           __lowercase      =						self.__class__.model_type
           return output










'''simple docstring'''
from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


A							:				Dict			     =	{
    """id""": """5733be284776f41900661182""",
    """title""": """University_of_Notre_Dame""",
    """context""": """Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.""",
    """question""": """To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?""",
    """answers""": {"""text""": ["""Saint Bernadette Soubirous"""], """answer_start""": [515]},
}
@pytest.mark.parametrize(
    """task_cls"""   ,[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]   ,)
def     snake_case_  (       a__		:     str      ):



    """simple docstring"""




    __lowercase          =						task_cls()
    __lowercase          =						asdict(a__      )
    __lowercase          =						task_template_from_dict(a__      )
    assert task == reloaded






class 	SCREAMING_SNAKE_CASE:

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						LanguageModeling(text_column="""input_text"""					)
           assert {"input_text": "text"} == task.column_mapping




       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text"""}
           __lowercase          =						LanguageModeling.from_dict(lowerCamelCase__					)
           assert "language-modeling" == task.task
           assert input_schema == task.input_schema






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{"""text_column""": """input_text""", """label_column""": """input_labels"""}
           __lowercase          =						TextClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""text-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

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

           """simple docstring"""



           __lowercase          =						QuestionAnsweringExtractive(
               context_column="""input_context""" ,		question_column="""input_question""" ,		answers_column="""input_answers"""					)
           self.assertDictEqual(
               {"""input_context""": """context""", """input_question""": """question""", """input_answers""": """answers"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						Features({"""question""": Value("""string"""					), """context""": Value("""string"""					)}					)
           __lowercase          =						Features(
               {
                   """answers""": Sequence(
                       {
                           """text""": Value("""string"""					),
                           """answer_start""": Value("""int32"""					),
                       }					)
               }					)
           __lowercase          =						{
               """context_column""": """input_input_context""",
               """question_column""": """input_question""",
               """answers_column""": """input_answers""",
           }
           __lowercase          =						QuestionAnsweringExtractive.from_dict(lowerCamelCase__					)
           self.assertEqual("""question-answering-extractive""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           __lowercase          =						Summarization(text_column="""input_text""" ,		summary_column="""input_summary"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_summary""": """summary"""} ,		task.column_mapping					)




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

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						Features({"""summary""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text""", """summary_column""": """input_summary"""}
           __lowercase          =						Summarization.from_dict(lowerCamelCase__					)
           self.assertEqual("""summarization""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AutomaticSpeechRecognition(audio_column="""input_audio""" ,		transcription_column="""input_transcription"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_transcription""": """transcription"""} ,		task.column_mapping					)




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

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""transcription""": Value("""string"""					)}					)
           __lowercase          =						{
               """audio_column""": """input_audio""",
               """transcription_column""": """input_transcription""",
           }
           __lowercase          =						AutomaticSpeechRecognition.from_dict(lowerCamelCase__					)
           self.assertEqual("""automatic-speech-recognition""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

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

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """audio_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						AudioClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""audio-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

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

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_image""": """image""", """input_label""": """labels"""} ,		task.column_mapping					)

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

           """simple docstring"""



           __lowercase          =						Features({"""image""": Image()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """image_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						ImageClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""image-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
           __lowercase          =						Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()} ,		info=lowerCamelCase__					)
           assert isinstance(dataset.info.task_templates ,		lowerCamelCase__					)
           assert len(dataset.info.task_templates					) == 1

           def keep_task(lowerCamelCase__					):
               return x

           def dont_keep_task(lowerCamelCase__					):
               __lowercase          =						deepcopy(lowerCamelCase__					)
               __lowercase          =						0
               return out

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




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

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					), """label""": ClassLabel(names=("""pos""", """neg""")					)}					)
           __lowercase          =						TextClassification(text_column="""text""" ,		label_column="""label"""					)
           __lowercase          =						DatasetInfo(features=lowerCamelCase__ ,		task_templates=lowerCamelCase__					)
           __lowercase          =						Dataset.from_dict({"""text""": ["""A sentence."""], """label""": ["""pos"""]} ,		info=lowerCamelCase__					)

           def process(lowerCamelCase__					):
               return example

           __lowercase          =						dataset.remove_columns("""label"""					)
           __lowercase          =						modified_dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




