



"""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           =							logging.get_logger(__name__)


__a           =							{
    "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           =							"\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 							lowerCamelCase    (     _lowerCAmelCase							):






					'''simple docstring'''





					_A						:     Optional[Any]		=	"""bark_module"""
					_A						:     Optional[int]		=	["""past_key_values"""]

					_A						:     Union[str, Any]		=	{
					    """num_attention_heads""": """num_heads""",
					    """num_hidden_layers""": """num_layers""",
					    """vocab_size""": """input_vocab_size""",
					    """window_size""": """block_size""",
					}






					def __init__(			self:				Any		,	snake_case:				Any=1_024		,	snake_case:				int=10_048		,	snake_case:				int=10_048		,	snake_case:				Union[str, Any]=12		,	snake_case:				List[Any]=12		,	snake_case:				str=768		,	snake_case:				Union[str, Any]=0.0		,	snake_case:				List[Any]=True		,	snake_case:				List[Any]=0.0_2		,	snake_case:				List[Any]=True		,	**snake_case:				Tuple		,	)  ->      Tuple:
											snake_case_					:Optional[int]		=     block_size
											snake_case_					:str		=     input_vocab_size
											snake_case_					:List[str]		=     output_vocab_size
											snake_case_					:int		=     num_layers
											snake_case_					:List[str]		=     num_heads
											snake_case_					:Any		=     hidden_size
											snake_case_					:Optional[Any]		=     dropout
											snake_case_					:Any		=     bias
											snake_case_					:List[Any]		=     use_cache
											snake_case_					:str		=     initializer_range

											super().__init__(**snake_case		)






					@classmethod
					def   lowerCAmelCase_							(			cls:				List[Any]		,	snake_case:				Union[str, os.PathLike]		,	snake_case:				Optional[Union[str, os.PathLike]] = None		,	snake_case:				bool = False		,	snake_case:				bool = False		,	snake_case:				Optional[Union[str, bool]] = None		,	snake_case:				str = "main"		,	**snake_case:				Dict		,	)  ->      "PretrainedConfig":
											snake_case_					:Optional[Any]		=     cache_dir
											snake_case_					:List[Any]		=     force_download
											snake_case_					:List[str]		=     local_files_only
											snake_case_					:Dict		=     revision

											cls._set_token_in_kwargs(snake_case		,	snake_case		)

											snake_case_,			snake_case_					:int		=     cls.get_config_dict(snake_case		,	**snake_case		)

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

@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 							lowerCamelCase    (     _lowerCAmelCase							):






					'''simple docstring'''





					_A						:     List[Any]		=	"""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 							lowerCamelCase    (     _lowerCAmelCase							):






					'''simple docstring'''





					_A						:     Any		=	"""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 							lowerCamelCase    (     _lowerCAmelCase							):






					'''simple docstring'''





					_A						:     Optional[int]		=	"""fine_acoustics"""






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

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

class 							lowerCamelCase    (     _lowerCAmelCase							):






					'''simple docstring'''





					_A						:     Union[str, Any]		=	"""bark"""
					_A						:     List[str]		=	True






					def __init__(			self:				Any		,	snake_case:				Dict = None		,	snake_case:				Dict = None		,	snake_case:				Dict = None		,	snake_case:				Dict = None		,	snake_case:				Union[str, Any]=0.0_2		,	**snake_case:				Tuple		,	)  ->      str:
											if semantic_config is None:
																	snake_case_					:List[str]		=     {}
																	logger.info("""semantic_config is None. initializing the semantic model with default values."""		)

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

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

											if codec_config is None:
																	snake_case_					:Union[str, Any]		=     {}
																	logger.info("""codec_config is None. initializing the codec model with default values."""		)

											snake_case_					:List[str]		=     BarkSemanticConfig(**snake_case		)
											snake_case_					:Dict		=     BarkCoarseConfig(**snake_case		)
											snake_case_					:Optional[int]		=     BarkFineConfig(**snake_case		)
											snake_case_					:Dict		=     AutoConfig.for_model(**snake_case		)

											snake_case_					:Union[str, Any]		=     initializer_range

											super().__init__(**snake_case		)






					@classmethod
					def   lowerCAmelCase_							(			cls:				Tuple		,	snake_case:				BarkSemanticConfig		,	snake_case:				BarkCoarseConfig		,	snake_case:				BarkFineConfig		,	snake_case:				AutoConfig		,	**snake_case:				Any		,	)  ->      Tuple:
											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()		,	**snake_case		,	)






					def   lowerCAmelCase_							(			self:				List[str]		)  ->      Any:
											snake_case_					:Optional[int]		=     copy.deepcopy(self.__dict__		)

											snake_case_					:Dict		=     self.semantic_config.to_dict()
											snake_case_					:Tuple		=     self.coarse_acoustics_config.to_dict()
											snake_case_					:Tuple		=     self.fine_acoustics_config.to_dict()
											snake_case_					:Tuple		=     self.codec_config.to_dict()

											snake_case_					:Union[str, Any]		=     self.__class__.model_type
											return output

'''simple docstring'''

import unittest

import requests

from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
						from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
						A_	   = False


if is_vision_available():
						from PIL import Image
else:




						class 		SCREAMING_SNAKE_CASE_					:



									"""simple docstring"""






									@staticmethod
									def   lowerCamelCase (							*snake_case_				,			**snake_case_					):
															pass




@is_pipeline_test
@require_vision
class 		SCREAMING_SNAKE_CASE_					(unittest.TestCase      ):



			"""simple docstring"""






			__magic_name__ :				Optional[int]   							=       MODEL_FOR_VISION_2_SEQ_MAPPING
			__magic_name__ :				Optional[int]   							=       TF_MODEL_FOR_VISION_2_SEQ_MAPPING



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_				,			snake_case_					):
									snake_case :       str				=    pipeline("image-to-text"				,			model=snake_case_				,			tokenizer=snake_case_				,			image_processor=snake_case_					)
									snake_case :       List[Any]				=    [
									    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					),
									    "./tests/fixtures/tests_samples/COCO/000000039769.png",
									]
									return pipe, examples



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_					):
									snake_case :       Union[str, Any]				=    pipe(snake_case_					)
									self.assertEqual(
									    snake_case_				,			[
									        [{"generated_text": ANY(snake_case_					)}],
									        [{"generated_text": ANY(snake_case_					)}],
									    ]				,			)



			@require_tf
			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    pipeline("image-to-text"				,			model="hf-internal-testing/tiny-random-vit-gpt2"				,			framework="tf"					)
									snake_case :       Union[str, Any]				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Dict				=    pipe(snake_case_					)
									self.assertEqual(
									    snake_case_				,			[
									        {
									            "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									        },
									    ]				,			)

									snake_case :       Tuple				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									    ]				,			)

									snake_case :       List[Any]				=    pipe(snake_case_				,			max_new_tokens=1					)
									self.assertEqual(
									    snake_case_				,			[{"generated_text": "growth"}]				,			)



			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       List[Any]				=    pipeline("image-to-text"				,			model="hf-internal-testing/tiny-random-vit-gpt2"					)
									snake_case :       Tuple				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Any				=    pipe(snake_case_					)
									self.assertEqual(
									    snake_case_				,			[
									        {
									            "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									        },
									    ]				,			)

									snake_case :       str				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									    ]				,			)



			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    pipeline("image-to-text"				,			model="hf-internal-testing/tiny-random-BlipForConditionalGeneration"					)
									snake_case :       Dict				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"
									snake_case :       List[Any]				=    "a photo of"

									snake_case :       List[str]				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertTrue(outputs[0]["generated_text"].startswith(snake_case_					)					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Optional[Any]				=    pipeline("image-to-text"				,			model="ydshieh/vit-gpt2-coco-en"					)
									snake_case :       Union[str, Any]				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Tuple				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]					)

									snake_case :       Tuple				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									    ]				,			)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Optional[Any]				=    pipeline("image-to-text"				,			model="Salesforce/blip-image-captioning-base"					)
									snake_case :       Any				=    "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
									snake_case :       Union[str, Any]				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Optional[Any]				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a pink pokemon pokemon with a blue shirt and a blue shirt"}]					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    pipeline("image-to-text"				,			model="microsoft/git-base-coco"					)
									snake_case :       Tuple				=    "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
									snake_case :       Tuple				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Any				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a cartoon of a purple character."}]					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Optional[Any]				=    pipeline("image-to-text"				,			model="Salesforce/blip-image-captioning-base"					)
									snake_case :       int				=    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
									snake_case :       Tuple				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       str				=    "a photography of"

									snake_case :       int				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a photography of a volcano"}]					)

									with self.assertRaises(snake_case_					):
															snake_case :       List[Any]				=    pipe([image, image]				,			prompt=[prompt, prompt]					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    pipeline("image-to-text"				,			model="microsoft/git-base-coco"					)
									snake_case :       Optional[Any]				=    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
									snake_case :       List[str]				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Any				=    "a photo of a"

									snake_case :       Dict				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a photo of a tent with a tent and a tent in the background."}]					)

									with self.assertRaises(snake_case_					):
															snake_case :       List[str]				=    pipe([image, image]				,			prompt=[prompt, prompt]					)



			@unittest.skipIf(
			    not is_torch_greater_or_equal_than_1_11				,			reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."					)
			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    pipeline("image-to-text"				,			model="google/pix2struct-ai2d-base"					)
									snake_case :       Optional[int]				=    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
									snake_case :       str				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Any				=    "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"

									snake_case :       str				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "ash cloud"}]					)

									with self.assertRaises(snake_case_					):
															snake_case :       List[str]				=    pipe([image, image]				,			prompt=[prompt, prompt]					)






			@slow
			@require_tf
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    pipeline("image-to-text"				,			model="ydshieh/vit-gpt2-coco-en"				,			framework="tf"					)
									snake_case :       Union[str, Any]				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Any				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]					)

									snake_case :       Optional[int]				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									    ]				,			)





