

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


lowerCAmelCase_	     =     logging.get_logger(__name__)


lowerCAmelCase_	     =     {
    '''suno/bark-small''': '''https://huggingface.co/suno/bark-small/resolve/main/config.json''',
    '''suno/bark''': '''https://huggingface.co/suno/bark/resolve/main/config.json''',
}

lowerCAmelCase_	     =     '''
    This is the configuration class to store the configuration of a [`{model}`]. It is used to instantiate the model
    according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to that of the Bark [suno/bark](https://huggingface.co/suno/bark)
    architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        block_size (`int`, *optional*, defaults to 1024):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        input_vocab_size (`int`, *optional*, defaults to 10_048):
            Vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`{model}`]. Defaults to 10_048 but should be carefully thought with
            regards to the chosen sub-model.
        output_vocab_size (`int`, *optional*, defaults to 10_048):
            Output vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented
            by the: `output_ids` when passing forward a [`{model}`]. Defaults to 10_048 but should be carefully thought
            with regards to the chosen sub-model.
        num_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the given sub-model.
        num_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer architecture.
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the "intermediate" (often named feed-forward) layer in the architecture.
        dropout (`float`, *optional*, defaults to 0.0):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        bias (`bool`, *optional*, defaults to `True`):
            Whether or not to use bias in the linear layers and layer norm layers.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).
'''





class      snake_case_       (		__A ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       Optional[Any]						      =    "bark_module"
			SCREAMING_SNAKE_CASE					:       List[str]						      =    ["past_key_values"]

			SCREAMING_SNAKE_CASE					:       int						      =    {
			    "num_attention_heads": "num_heads",
			    "num_hidden_layers": "num_layers",
			    "vocab_size": "input_vocab_size",
			    "window_size": "block_size",
			}







			def __init__(					self			:    Any							,       _UpperCamelCase			:    Dict=1_0_2_4							,       _UpperCamelCase			:    Any=1_0_0_4_8							,       _UpperCamelCase			:    int=1_0_0_4_8							,       _UpperCamelCase			:    int=1_2							,       _UpperCamelCase			:    int=1_2							,       _UpperCamelCase			:    Dict=7_6_8							,       _UpperCamelCase			:    List[Any]=0.0							,       _UpperCamelCase			:    Any=True							,       _UpperCamelCase			:    int=0.02							,       _UpperCamelCase			:    Tuple=True							,       **_UpperCamelCase			:    Dict							,       )				->Dict:
									snake_case_       =     block_size
									snake_case_       =     input_vocab_size
									snake_case_       =     output_vocab_size
									snake_case_       =     num_layers
									snake_case_       =     num_heads
									snake_case_       =     hidden_size
									snake_case_       =     dropout
									snake_case_       =     bias
									snake_case_       =     use_cache
									snake_case_       =     initializer_range

									super().__init__(**_UpperCamelCase							)







			@classmethod
			def     snake_case__(					cls			:    int							,       _UpperCamelCase			:    Union[str, os.PathLike]							,       _UpperCamelCase			:    Optional[Union[str, os.PathLike]] = None							,       _UpperCamelCase			:    bool = False							,       _UpperCamelCase			:    bool = False							,       _UpperCamelCase			:    Optional[Union[str, bool]] = None							,       _UpperCamelCase			:    str = "main"							,       **_UpperCamelCase			:    int							,       )				->"PretrainedConfig":
									snake_case_       =     cache_dir
									snake_case_       =     force_download
									snake_case_       =     local_files_only
									snake_case_       =     revision

									cls._set_token_in_kwargs(_UpperCamelCase							,       _UpperCamelCase							)

									snake_case_,   snake_case_       =     cls.get_config_dict(_UpperCamelCase							,       **_UpperCamelCase							)

									# get the config dict if we are loading from Bark
									if config_dict.get('''model_type'''							) == "bark":
															snake_case_       =     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(_UpperCamelCase							,       **_UpperCamelCase							)






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkSemanticConfig"     ,	model="BarkSemanticModel" )     ,	"\n    Example:\n\n    ```python\n    >>> from transformers import BarkSemanticConfig, BarkSemanticModel\n\n    >>> # Initializing a Bark sub-module style configuration\n    >>> configuration = BarkSemanticConfig()\n\n    >>> # Initializing a model (with random weights) from the suno/bark style configuration\n    >>> model = BarkSemanticModel(configuration)\n\n    >>> # Accessing the model configuration\n    >>> configuration = model.config\n    ```"     ,	)
class      snake_case_       (		__A ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       Optional[int]						      =    "semantic"






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkCoarseConfig"     ,	model="BarkCoarseModel" )     ,	"\n    Example:\n\n    ```python\n    >>> from transformers import BarkCoarseConfig, BarkCoarseModel\n\n    >>> # Initializing a Bark sub-module style configuration\n    >>> configuration = BarkCoarseConfig()\n\n    >>> # Initializing a model (with random weights) from the suno/bark style configuration\n    >>> model = BarkCoarseModel(configuration)\n\n    >>> # Accessing the model configuration\n    >>> configuration = model.config\n    ```"     ,	)
class      snake_case_       (		__A ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       Union[str, Any]						      =    "coarse_acoustics"






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkFineConfig"     ,	model="BarkFineModel" )     ,	"\n        n_codes_total (`int`, *optional*, defaults to 8):\n            The total number of audio codebooks predicted. Used in the fine acoustics sub-model.\n        n_codes_given (`int`, *optional*, defaults to 1):\n            The number of audio codebooks predicted in the coarse acoustics sub-model. Used in the acoustics\n            sub-models.\n    Example:\n\n    ```python\n    >>> from transformers import BarkFineConfig, BarkFineModel\n\n    >>> # Initializing a Bark sub-module style configuration\n    >>> configuration = BarkFineConfig()\n\n    >>> # Initializing a model (with random weights) from the suno/bark style configuration\n    >>> model = BarkFineModel(configuration)\n\n    >>> # Accessing the model configuration\n    >>> configuration = model.config\n    ```"     ,	)
class      snake_case_       (		__A ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       Optional[int]						      =    "fine_acoustics"







			def __init__(					self			:    int							,       _UpperCamelCase			:    List[str]=True							,       _UpperCamelCase			:    List[str]=8							,       _UpperCamelCase			:    Tuple=1							,       **_UpperCamelCase			:    List[str]							)				->Dict:
									snake_case_       =     n_codes_total
									snake_case_       =     n_codes_given

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






class      snake_case_       (		__A ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       List[Any]						      =    "bark"
			SCREAMING_SNAKE_CASE					:       Dict						      =    True







			def __init__(					self			:    Optional[Any]							,       _UpperCamelCase			:    Dict = None							,       _UpperCamelCase			:    Dict = None							,       _UpperCamelCase			:    Dict = None							,       _UpperCamelCase			:    Dict = None							,       _UpperCamelCase			:    Union[str, Any]=0.02							,       **_UpperCamelCase			:    Any							,       )				->Dict:
									if semantic_config is None:
															snake_case_       =     {}
															logger.info('''semantic_config is None. initializing the semantic model with default values.'''							)

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

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

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

									snake_case_       =     BarkSemanticConfig(**_UpperCamelCase							)
									snake_case_       =     BarkCoarseConfig(**_UpperCamelCase							)
									snake_case_       =     BarkFineConfig(**_UpperCamelCase							)
									snake_case_       =     AutoConfig.for_model(**_UpperCamelCase							)

									snake_case_       =     initializer_range

									super().__init__(**_UpperCamelCase							)







			@classmethod
			def     snake_case__(					cls			:    Optional[Any]							,       _UpperCamelCase			:    BarkSemanticConfig							,       _UpperCamelCase			:    BarkCoarseConfig							,       _UpperCamelCase			:    BarkFineConfig							,       _UpperCamelCase			:    AutoConfig							,       **_UpperCamelCase			:    Dict							,       )				->str:
									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()							,       **_UpperCamelCase							,       )







			def     snake_case__(					self			:    Union[str, Any]							)				->Tuple:
									snake_case_       =     copy.deepcopy(self.__dict__							)

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

									snake_case_       =     self.__class__.model_type
									return output


import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class      snake_case_       (		__A     ,	unittest.TestCase ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       str						      =    PreTrainedTokenizerFast
			SCREAMING_SNAKE_CASE					:       List[str]						      =    False
			SCREAMING_SNAKE_CASE					:       Tuple						      =    True
			SCREAMING_SNAKE_CASE					:       str						      =    "tokenizer_file"







			def     snake_case__(					self			:    Dict							)				->int:
									snake_case_       =     False  # because we don't have pretrained_vocab_files_map
									super().setUp()
									snake_case_       =     True

									snake_case_       =     ['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
									snake_case_       =     '''SaulLu/dummy-tokenizer-bytelevel-bpe'''

									# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
									snake_case_       =     [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

									snake_case_       =     PreTrainedTokenizerFast.from_pretrained(model_paths[0]							)
									tokenizer.save_pretrained(self.tmpdirname							)







			def     snake_case__(					self			:    Union[str, Any]							)				->Dict:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    str							)				->Any:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    List[Any]							)				->str:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    str							)				->List[Any]:
									# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
									pass







			def     snake_case__(					self			:    Any							)				->Union[str, Any]:
									snake_case_       =     self.tmpdirname
									# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''							):
																					try:
																											snake_case_       =     tempfile.mkdtemp()
																											snake_case_       =     self.rust_tokenizer_class.from_pretrained(_UpperCamelCase							,       **_UpperCamelCase							)

																											tokenizer.save_pretrained(self.tmpdirname							)
																											super().test_training_new_tokenizer()
																					finally:
																											# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																											# is restored
																											shutil.rmtree(self.tmpdirname							)
																											snake_case_       =     tmpdirname_orig







			def     snake_case__(					self			:    List[str]							)				->List[Any]:
									snake_case_       =     self.tmpdirname
									# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''							):
																					try:
																											snake_case_       =     tempfile.mkdtemp()
																											snake_case_       =     self.rust_tokenizer_class.from_pretrained(_UpperCamelCase							,       **_UpperCamelCase							)

																											tokenizer.save_pretrained(self.tmpdirname							)
																											super().test_training_new_tokenizer_with_special_tokens_change()
																					finally:
																											# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																											# is restored
																											shutil.rmtree(self.tmpdirname							)
																											snake_case_       =     tmpdirname_orig







			def     snake_case__(					self			:    Optional[int]							)				->Optional[Any]:
									snake_case_       =     self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name							)

									snake_case_       =     ('''a''' for _ in range(1_0_0_0							))
									snake_case_       =     tokenizer.train_new_from_iterator(text_iterator=_UpperCamelCase							,       length=1_0_0_0							,       vocab_size=5_0							)

									snake_case_       =     new_tokenizer.encode('''a🤗'''							)
									self.assertEqual(_UpperCamelCase							,       [6_4, 1_7_2, 2_5_3, 9_7, 2_4_5]							)






@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

			def     snake_case__(					self			:    Optional[int]							)				->int:
									snake_case_       =     AutoTokenizer.from_pretrained('''bert-base-cased'''							)
									snake_case_       =     json.loads(tokenizer._tokenizer.to_str()							)
									snake_case_       =     len(_UpperCamelCase							)

									with tempfile.TemporaryDirectory() as tmp_dir:
															# Hack to save this in the tokenizer_config.json
															snake_case_       =     ['''tokenizer.4.0.0.json''']
															tokenizer.save_pretrained(_UpperCamelCase							)
															json.dump(_UpperCamelCase							,       open(os.path.join(_UpperCamelCase							,       '''tokenizer.4.0.0.json'''							)							,       '''w'''							)							)

															# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
															snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
															self.assertEqual(len(_UpperCamelCase							)							,       len(_UpperCamelCase							) + 1							)
															snake_case_       =     json.loads(new_tokenizer._tokenizer.to_str()							)
															self.assertIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)

															# Will need to be adjusted if we reach v42 and this test is still here.
															# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
															shutil.move(os.path.join(_UpperCamelCase							,       '''tokenizer.4.0.0.json'''							)							,       os.path.join(_UpperCamelCase							,       '''tokenizer.42.0.0.json'''							)							)
															snake_case_       =     ['''tokenizer.42.0.0.json''']
															tokenizer.save_pretrained(_UpperCamelCase							)
															snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
															self.assertEqual(len(_UpperCamelCase							)							,       len(_UpperCamelCase							)							)
															snake_case_       =     json.loads(new_tokenizer._tokenizer.to_str()							)
															self.assertNotIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)







			def     snake_case__(					self			:    List[str]							)				->Optional[Any]:
									# This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
									snake_case_       =     '''hf-internal-testing/test-two-tokenizers'''

									# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
									snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
									self.assertEqual(len(_UpperCamelCase							)							,       2_8_9_9_7							)
									snake_case_       =     json.loads(tokenizer._tokenizer.to_str()							)
									self.assertIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)

									# Testing an older version by monkey-patching the version in the module it's used.
									import transformers as old_transformers

									snake_case_       =     '''3.0.0'''
									snake_case_       =     old_transformers.models.auto.AutoTokenizer.from_pretrained(_UpperCamelCase							)
									self.assertEqual(len(_UpperCamelCase							)							,       2_8_9_9_6							)
									snake_case_       =     json.loads(old_tokenizer._tokenizer.to_str()							)
									self.assertNotIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)






@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

			def     snake_case__(					self			:    str							)				->Optional[int]:
									# See https://github.com/huggingface/transformers/pull/12550
									# and https://github.com/huggingface/tokenizers/issues/537
									snake_case_       =     PreTrainedTokenizerFast.from_pretrained('''robot-test/dummy-tokenizer-wordlevel'''							)
									snake_case_       =     '''The Matrix is a 1999 science fiction action film.'''

									with concurrent.futures.ThreadPoolExecutor() as executor:
															snake_case_       =     [executor.submit(self.fetch							,       _UpperCamelCase							,       _UpperCamelCase							) for i in range(1_0							)]
															snake_case_       =     [future.result() for future in futures]
															self.assertEqual(_UpperCamelCase							,       [[1, 1_0, 0, 8, 0, 1_8, 0, 0, 0, 2] for i in range(1_0							)]							)







			def     snake_case__(					self			:    Optional[int]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    str							)				->Tuple:
									return tokenizer.encode(_UpperCamelCase							,       truncation='''longest_first'''							,       padding='''longest'''							)