




from sklearn.metrics import precision_score

import datasets


__lowerCAmelCase				      =					'\nPrecision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:\nPrecision = TP / (TP + FP)\nwhere TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).\n'


__lowerCAmelCase				      =					'\nArgs:\n    predictions (`list` of `int`): Predicted class labels.\n    references (`list` of `int`): Actual class labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to \'warn\'.\n\n        - 0: Returns 0 when there is a zero division.\n        - 1: Returns 1 when there is a zero division.\n        - \'warn\': Raises warnings and then returns 0 when there is a zero division.\n\nReturns:\n    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {\'precision\': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results[\'precision\'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(results)\n        {\'precision\': 0.23529411764705882}\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'precision\': 0.3333333333333333}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print([round(res, 2) for res in results[\'precision\']])\n        [0.67, 0.0, 0.0]\n'


__lowerCAmelCase				      =					'\n@article{scikit-learn,\n    title={Scikit-learn: Machine Learning in {P}ython},\n    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n    and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n    and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n    Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n    journal={Journal of Machine Learning Research},\n    volume={12},\n    pages={2825--2830},\n    year={2011}\n}\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,		_KWARGS_DESCRIPTION				)
class 						lowerCamelCase			(					datasets.Metric				):







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







				"""simple docstring"""






				return datasets.MetricInfo(
				    description=_DESCRIPTION      ,    citation=_CITATION      ,    inputs_description=_KWARGS_DESCRIPTION      ,    features=datasets.Features(
				        {
				            '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ),
				            '''references''': datasets.Sequence(datasets.Value('''int32''' ) ),
				        }
				        if self.config_name == '''multilabel'''
				        else {
				            '''predictions''': datasets.Value('''int32''' ),
				            '''references''': datasets.Value('''int32''' ),
				        } )      ,    reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html''']      ,    )







	def    snake_case__    (    self			:Optional[int]      ,    lowercase			:List[str]      ,    lowercase			:Dict      ,    lowercase			:Tuple=None      ,    lowercase			:int=1      ,    lowercase			:int="binary"      ,    lowercase			:Dict=None      ,    lowercase			:Optional[int]="warn"      ,    )		->			Tuple:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE    	=   precision_score(
				    lowercase      ,    lowercase      ,    labels=lowercase      ,    pos_label=lowercase      ,    average=lowercase      ,    sample_weight=lowercase      ,    zero_division=lowercase      ,    )
				return {"precision": float(lowercase ) if score.size == 1 else score}

import copy

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


__lowerCAmelCase				      =					logging.get_logger(__name__)

__lowerCAmelCase				      =					{
    '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 						lowerCamelCase			(					__lowerCamelCase				):
	UpperCamelCase_     :				int								=  'musicgen_decoder'
	UpperCamelCase_     :				Optional[int]								=  ['past_key_values']







	def __init__(    self			:List[str]      ,    lowercase			:Tuple=2_0_4_8      ,    lowercase			:Dict=2_0_4_8      ,    lowercase			:Tuple=2_4      ,    lowercase			:Any=4_0_9_6      ,    lowercase			:Optional[Any]=1_6      ,    lowercase			:List[Any]=0.0      ,    lowercase			:Union[str, Any]=True      ,    lowercase			:Optional[Any]="gelu"      ,    lowercase			:Any=1_0_2_4      ,    lowercase			:str=0.1      ,    lowercase			:List[Any]=0.0      ,    lowercase			:List[Any]=0.0      ,    lowercase			:List[Any]=0.02      ,    lowercase			:Optional[int]=False      ,    lowercase			:List[Any]=4      ,    lowercase			:Any=2_0_4_8      ,    lowercase			:Any=2_0_4_8      ,    lowercase			:Optional[int]=None      ,    lowercase			:Tuple=False      ,    **lowercase			:List[Any]      ,    )		->			Tuple:







				"""simple docstring"""






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





class 						lowerCamelCase			(					__lowerCamelCase				):
	UpperCamelCase_     :				str								=  'musicgen'
	UpperCamelCase_     :				Union[str, Any]								=  True







	def __init__(    self			:str      ,    **lowercase			:int )		->			Optional[Any]:







				"""simple docstring"""






				super().__init__(**lowercase )
				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''' )

				SCREAMING_SNAKE_CASE    	=   kwargs.pop('''text_encoder''' )
				SCREAMING_SNAKE_CASE    	=   text_encoder_config.pop('''model_type''' )

				SCREAMING_SNAKE_CASE    	=   kwargs.pop('''audio_encoder''' )
				SCREAMING_SNAKE_CASE    	=   audio_encoder_config.pop('''model_type''' )

				SCREAMING_SNAKE_CASE    	=   kwargs.pop('''decoder''' )

				SCREAMING_SNAKE_CASE    	=   AutoConfig.for_model(lowercase      ,    **lowercase )
				SCREAMING_SNAKE_CASE    	=   AutoConfig.for_model(lowercase      ,    **lowercase )
				SCREAMING_SNAKE_CASE    	=   MusicgenDecoderConfig(**lowercase )
				SCREAMING_SNAKE_CASE    	=   True







	@classmethod
	def    snake_case__    (    cls			:Tuple      ,    lowercase			:PretrainedConfig      ,    lowercase			:PretrainedConfig      ,    lowercase			:MusicgenDecoderConfig      ,    **lowercase			:Tuple      ,    )		->			Tuple:







				"""simple docstring"""






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







	def    snake_case__    (    self			:Dict )		->			Dict:







				"""simple docstring"""






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