






"""simple docstring"""





from sklearn.metrics import precision_score

import datasets


UpperCamelCase					=     """
Precision 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:
Precision = TP / (TP + FP)
where 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).
"""


UpperCamelCase					=     """
Args:
    predictions (`list` of `int`): Predicted class labels.
    references (`list` of `int`): Actual class labels.
    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.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    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'`.

        - '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.
        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - '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.
        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.
    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to 'warn'.

        - 0: Returns 0 when there is a zero division.
        - 1: Returns 1 when there is a zero division.
        - 'warn': Raises warnings and then returns 0 when there is a zero division.

Returns:
    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.

Examples:

    Example 1-A simple binary example
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'precision': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['precision'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> 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])
        >>> print(results)
        {'precision': 0.23529411764705882}

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'precision': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'precision': 0.3333333333333333}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'precision': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)
        >>> print([round(res, 2) for res in results['precision']])
        [0.67, 0.0, 0.0]
"""


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







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





   '''simple docstring'''






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




          '''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 __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_=None					, UpperCAmelCase_=1					, UpperCAmelCase_="binary"					, UpperCAmelCase_=None					, UpperCAmelCase_="warn"					, )			->   Dict:




          '''simple docstring'''




          lowercase__:							Tuple         =     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}











'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import BlipImageProcessor



class 				lowercase			(    unittest.TestCase							):


 """simple docstring"""


 def __init__(				self    ,a_    ,a_=7    ,a_=3    ,a_=18    ,a_=30    ,a_=400    ,a_=True    ,a_=None    ,a_=True    ,a_=False    ,a_=[0.4814_5466, 0.457_8275, 0.4082_1073]    ,a_=[0.2686_2954, 0.2613_0258, 0.2757_7711]    ,a_=True    ,)						->  Optional[int]:
        _UpperCAmelCase    :		Dict     	=					size if size is not None else {"""height""": 20, """width""": 20}
        _UpperCAmelCase    :		Dict     	=					parent
        _UpperCAmelCase    :		Tuple     	=					batch_size
        _UpperCAmelCase    :		Optional[int]     	=					num_channels
        _UpperCAmelCase    :		int     	=					image_size
        _UpperCAmelCase    :		List[Any]     	=					min_resolution
        _UpperCAmelCase    :		str     	=					max_resolution
        _UpperCAmelCase    :		Tuple     	=					do_resize
        _UpperCAmelCase    :		Union[str, Any]     	=					size
        _UpperCAmelCase    :		int     	=					do_normalize
        _UpperCAmelCase    :		List[str]     	=					image_mean
        _UpperCAmelCase    :		Any     	=					image_std
        _UpperCAmelCase    :		Union[str, Any]     	=					do_pad
        _UpperCAmelCase    :		Tuple     	=					do_convert_rgb







 def _snake_case					(				self				)						->  List[str]:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_convert_rgb": self.do_convert_rgb,
            "do_pad": self.do_pad,
        }







 def _snake_case					(				self    ,a_=False    ,a_=False    ,a_=False				)						->  Dict:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
               _UpperCAmelCase    :		Union[str, Any]     	=					[]
               for i in range(self.batch_size				):
                      image_inputs.append(
                          np.random.randint(
                              255    ,size=(self.num_channels, self.max_resolution, self.max_resolution)    ,dtype=np.uinta				)				)
        else:
               _UpperCAmelCase    :		Optional[int]     	=					[]
               for i in range(self.batch_size				):
                      _UpperCAmelCase	,_UpperCAmelCase    :		int     	=					np.random.choice(np.arange(self.min_resolution    ,self.max_resolution				)    ,2				)
                      image_inputs.append(np.random.randint(255    ,size=(self.num_channels, width, height)    ,dtype=np.uinta				)				)

        if not numpify and not torchify:
               # PIL expects the channel dimension as last dimension
               _UpperCAmelCase    :		Any     	=					[Image.fromarray(np.moveaxis(a_    ,0    ,-1				)				) for x in image_inputs]

        if torchify:
               _UpperCAmelCase    :		Optional[int]     	=					[torch.from_numpy(a_				) for x in image_inputs]

        return image_inputs







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  List[Any]:
        _UpperCAmelCase    :		Dict     	=					BlipImageProcessingTester(self				)







 @property
 def _snake_case					(				self				)						->  str:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Tuple:
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







 def _snake_case					(				self				)						->  Any:
        pass







 def _snake_case					(				self				)						->  Union[str, Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[str]     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		List[str]     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







 def _snake_case					(				self				)						->  Optional[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		str     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,numpify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,np.ndarray				)

        # Test not batched input
        _UpperCAmelCase    :		Dict     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		int     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







 def _snake_case					(				self				)						->  List[str]:
        # Initialize image_processor
        _UpperCAmelCase    :		Dict     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        _UpperCAmelCase    :		Union[str, Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,torchify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,torch.Tensor				)

        # Test not batched input
        _UpperCAmelCase    :		str     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		Optional[Any]     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					BlipImageProcessingTester(self    ,num_channels=4				)
        _UpperCAmelCase    :		List[Any]     	=					3







 @property
 def _snake_case					(				self				)						->  int:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







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







 def _snake_case					(				self				)						->  List[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		Any     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[Any]     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		Dict     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)



