




from sklearn.metrics import precision_score

import datasets


_lowerCamelCase					:     Tuple					  =  "\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					:     List[Any]					  =  "\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					:     Optional[int]					  =  "\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 				__snake_case     (datasets.Metric						):



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			Dict:





								'''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 					SCREAMING_SNAKE_CASE				(					self					:						Union[str, Any]						,		_UpperCAmelCase					:						List[str]						,		_UpperCAmelCase					:						Optional[int]						,		_UpperCAmelCase					:						Optional[int]=None						,		_UpperCAmelCase					:						Union[str, Any]=1						,		_UpperCAmelCase					:						Optional[Any]="binary"						,		_UpperCAmelCase					:						Union[str, Any]=None						,		_UpperCAmelCase					:						Tuple="warn"						,		)     ->			str:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					precision_score(
								    _UpperCAmelCase						,		_UpperCAmelCase						,		labels=_UpperCAmelCase						,		pos_label=_UpperCAmelCase						,		average=_UpperCAmelCase						,		sample_weight=_UpperCAmelCase						,		zero_division=_UpperCAmelCase						,		)
								return {"precision": float(_UpperCAmelCase					) if score.size == 1 else score}







import numpy as np  # noqa: E402

from ...configuration_utils import ConfigMixin, register_to_config
from ...schedulers.scheduling_utils import SchedulerMixin


try:
	import librosa  # noqa: E402

	_lowerCamelCase					:     Union[str, Any]					  =  True
	_lowerCamelCase					:     Optional[Any]					  =  ""
except Exception as e:
	_lowerCamelCase					:     int					  =  False
	_lowerCamelCase					:     List[str]					  =  (
	    F'''Cannot import librosa because {e}. Make sure to correctly install librosa to be able to install it.'''
	)


from PIL import Image  # noqa: E402
class 				__snake_case     (_a  ,		_a						):
				lowerCAmelCase__			=   "mel_config.json"



				@register_to_config
				def __init__(					self					:						Dict						,		_UpperCAmelCase					:						int = 256						,		_UpperCAmelCase					:						int = 256						,		_UpperCAmelCase					:						int = 2_2050						,		_UpperCAmelCase					:						int = 2048						,		_UpperCAmelCase					:						int = 512						,		_UpperCAmelCase					:						int = 80						,		_UpperCAmelCase					:						int = 32						,		)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					hop_length
								_lowerCAmelCase			:			Optional[Any]        =					sample_rate
								_lowerCAmelCase			:			Optional[Any]        =					n_fft
								_lowerCAmelCase			:			Dict        =					top_db
								_lowerCAmelCase			:			List[Any]        =					n_iter
								self.set_resolution(_UpperCAmelCase						,		_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					None

								if not _librosa_can_be_imported:
												raise ValueError(_import_error					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]						,		_UpperCAmelCase					:						int						,		_UpperCAmelCase					:						int					)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			Dict        =					x_res
								_lowerCAmelCase			:			Union[str, Any]        =					y_res
								_lowerCAmelCase			:			Any        =					self.y_res
								_lowerCAmelCase			:			Optional[Any]        =					self.x_res * self.hop_length - 1



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						str = None						,		_UpperCAmelCase					:						np.ndarray = None					)     ->			List[str]:





								'''simple docstring'''




								if audio_file is not None:
												_lowerCAmelCase    ,			_lowerCAmelCase			:			Dict        =					librosa.load(_UpperCAmelCase						,		mono=_UpperCAmelCase						,		sr=self.sr					)
								else:
												_lowerCAmelCase			:			Any        =					raw_audio

								# Pad with silence if necessary.
								if len(self.audio					) < self.x_res * self.hop_length:
												_lowerCAmelCase			:			Optional[Any]        =					np.concatenate([self.audio, np.zeros((self.x_res * self.hop_length - len(self.audio					),)					)]					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			int:





								'''simple docstring'''




								return len(self.audio					) // self.slice_size



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[str]						,		_UpperCAmelCase					:						int = 0					)     ->			np.ndarray:





								'''simple docstring'''




								return self.audio[self.slice_size * slice : self.slice_size * (slice + 1)]



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[Any]					)     ->			int:





								'''simple docstring'''




								return self.sr



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						int					)     ->			Image.Image:





								'''simple docstring'''




								_lowerCAmelCase			:			Union[str, Any]        =					librosa.feature.melspectrogram(
								    y=self.get_audio_slice(_UpperCAmelCase					)						,		sr=self.sr						,		n_fft=self.n_fft						,		hop_length=self.hop_length						,		n_mels=self.n_mels					)
								_lowerCAmelCase			:			List[Any]        =					librosa.power_to_db(_UpperCAmelCase						,		ref=np.max						,		top_db=self.top_db					)
								_lowerCAmelCase			:			List[Any]        =					(((log_S + self.top_db) * 255 / self.top_db).clip(0						,		255					) + 0.5).astype(np.uinta					)
								_lowerCAmelCase			:			Optional[Any]        =					Image.fromarray(_UpperCAmelCase					)
								return image



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]						,		_UpperCAmelCase					:						Image.Image					)     ->			np.ndarray:





								'''simple docstring'''




								_lowerCAmelCase			:			Optional[int]        =					np.frombuffer(image.tobytes()						,		dtype="""uint8"""					).reshape((image.height, image.width)					)
								_lowerCAmelCase			:			Optional[int]        =					bytedata.astype("""float"""					) * self.top_db / 255 - self.top_db
								_lowerCAmelCase			:			List[Any]        =					librosa.db_to_power(_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					librosa.feature.inverse.mel_to_audio(
								    _UpperCAmelCase						,		sr=self.sr						,		n_fft=self.n_fft						,		hop_length=self.hop_length						,		n_iter=self.n_iter					)
								return audio

