





'''simple docstring'''


from sklearn.metrics import precision_score

import datasets


lowerCAmelCase      :  Optional[Any]      							='''\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      :  Union[str, 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      :  Union[str, Any]      							='''\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    a_     (       datasets.Metric							):





     def 							lowercase__   (				self	:      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	:      List[str]			,   lowercase	:      str			,   lowercase	:      List[Any]			,   lowercase	:      Dict=None			,   lowercase	:      Tuple=1			,   lowercase	:      Optional[Any]="binary"			,   lowercase	:      Optional[int]=None			,   lowercase	:      Optional[Any]="warn"			,   ):





        """simple docstring"""




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









'''simple docstring'''


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


lowerCAmelCase      :  Any      							=logging.get_logger(__name__)
class    a_     (       _lowerCAmelCase							):
     __A  				=    ["pixel_values"]





     def __init__(				self	:      Tuple			,   lowercase	:      bool = True			,   lowercase	:      Dict[str, int] = None			,   lowercase	:      bool = True			,   lowercase	:      Dict[str, int] = None			,   lowercase	:      PILImageResampling = PILImageResampling.BICUBIC			,   lowercase	:      bool = True			,   lowercase	:      Union[int, float] = 1 / 255			,   lowercase	:      bool = True			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   **lowercase	:      int			,   ):





        """simple docstring"""




        super().__init__(**lowercase		)
        lowercase_    :Dict					    =				crop_size if crop_size is not None else {"height": 256, "width": 256}
        lowercase_    :str					    =				get_size_dict(lowercase			,   param_name="crop_size"		)
        lowercase_    :Optional[Any]					    =				size if size is not None else {"height": 224, "width": 224}
        lowercase_    :Union[str, Any]					    =				get_size_dict(lowercase		)

        lowercase_    :Union[str, Any]					    =				do_center_crop
        lowercase_    :str					    =				crop_size
        lowercase_    :List[str]					    =				do_resize
        lowercase_    :str					    =				size
        lowercase_    :Tuple					    =				resample
        lowercase_    :int					    =				do_rescale
        lowercase_    :Union[str, Any]					    =				rescale_factor
        lowercase_    :Tuple					    =				do_normalize
        lowercase_    :List[Any]					    =				image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        lowercase_    :Optional[int]					    =				image_std if image_std is not None else IMAGENET_DEFAULT_STD





     def 							lowercase__   (				self	:      Any			,   lowercase	:      np.ndarray			,   lowercase	:      Dict[str, int]			,   lowercase	:      Optional[int] = None			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      List[Any]			,   ):





        """simple docstring"""




        lowercase_    :Dict					    =				self.size if size is None else size
        lowercase_    :Dict					    =				get_size_dict(lowercase		)
        lowercase_    :List[Any]					    =				get_size_dict(lowercase			,   param_name="crop_size"		)

        lowercase_    ,							lowercase_    :List[str]					    =				get_image_size(lowercase		)
        lowercase_    :List[str]					    =				min(lowercase			,   lowercase		)
        lowercase_    :Tuple					    =				(size["height"] / crop_size["height"]) * min_dim
        lowercase_    :int					    =				(size["width"] / crop_size["width"]) * min_dim
        return center_crop(lowercase			,   size=(cropped_height, cropped_width)			,   data_format=lowercase			,   **lowercase		)





     def 							lowercase__   (				self	:      Union[str, Any]			,   lowercase	:      np.ndarray			,   lowercase	:      Dict[str, int]			,   lowercase	:      PILImageResampling = PIL.Image.BICUBIC			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      List[str]			,   ):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				get_size_dict(lowercase		)
        if "height" not in size or "width" not in size:
           raise ValueError(F'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'		)
        return resize(
            lowercase			,   size=(size["height"], size["width"])			,   resample=lowercase			,   data_format=lowercase			,   **lowercase		)





     def 							lowercase__   (				self	:      List[str]			,   lowercase	:      np.ndarray			,   lowercase	:      Union[int, float]			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      Union[str, Any]			,   ):





        """simple docstring"""




        return rescale(lowercase			,   scale=lowercase			,   data_format=lowercase			,   **lowercase		)





     def 							lowercase__   (				self	:      List[str]			,   lowercase	:      np.ndarray			,   lowercase	:      Union[float, List[float]]			,   lowercase	:      Union[float, List[float]]			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      str			,   ):





        """simple docstring"""




        return normalize(lowercase			,   mean=lowercase			,   std=lowercase			,   data_format=lowercase			,   **lowercase		)







     def 							lowercase__   (				self	:      List[Any]			,   lowercase	:      ImageInput			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[Dict[str, int]] = None			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[Dict[str, int]] = None			,   lowercase	:      PILImageResampling = None			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[float] = None			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   lowercase	:      Optional[Union[str, TensorType]] = None			,   lowercase	:      ChannelDimension = ChannelDimension.FIRST			,   **lowercase	:      Optional[Any]			,   ):





        """simple docstring"""




        lowercase_    :str					    =				do_center_crop if do_center_crop is not None else self.do_center_crop
        lowercase_    :Union[str, Any]					    =				crop_size if crop_size is not None else self.crop_size
        lowercase_    :Optional[Any]					    =				get_size_dict(lowercase			,   param_name="crop_size"		)
        lowercase_    :Union[str, Any]					    =				do_resize if do_resize is not None else self.do_resize
        lowercase_    :Any					    =				size if size is not None else self.size
        lowercase_    :List[Any]					    =				get_size_dict(lowercase		)
        lowercase_    :Optional[Any]					    =				resample if resample is not None else self.resample
        lowercase_    :Dict					    =				do_rescale if do_rescale is not None else self.do_rescale
        lowercase_    :List[Any]					    =				rescale_factor if rescale_factor is not None else self.rescale_factor
        lowercase_    :str					    =				do_normalize if do_normalize is not None else self.do_normalize
        lowercase_    :Dict					    =				image_mean if image_mean is not None else self.image_mean
        lowercase_    :List[Any]					    =				image_std if image_std is not None else self.image_std

        lowercase_    :Any					    =				make_list_of_images(lowercase		)

        if not valid_images(lowercase		):
           raise ValueError(
               "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
               "torch.Tensor, tf.Tensor or jax.ndarray."		)

        if do_center_crop and crop_size is None:
           raise ValueError("If `do_center_crop` is set to `True`, `crop_size` must be provided."		)

        if do_resize and size is None:
           raise ValueError("Size must be specified if do_resize is True."		)

        if do_rescale and rescale_factor is None:
           raise ValueError("Rescale factor must be specified if do_rescale is True."		)

        if do_normalize and (image_mean is None or image_std is None):
           raise ValueError("Image mean and image standard deviation must be specified if do_normalize is True."		)

        # All transformations expect numpy arrays.
        lowercase_    :Optional[int]					    =				[to_numpy_array(lowercase		) for image in images]

        if do_center_crop:
           lowercase_    :str					    =				[self.center_crop(lowercase			,   lowercase			,   size=lowercase		) for image in images]

        if do_resize:
           lowercase_    :List[str]					    =				[self.resize(image=lowercase			,   size=lowercase			,   resample=lowercase		) for image in images]

        if do_rescale:
           lowercase_    :List[Any]					    =				[self.rescale(image=lowercase			,   scale=lowercase		) for image in images]

        if do_normalize:
           lowercase_    :Optional[Any]					    =				[self.normalize(image=lowercase			,   mean=lowercase			,   std=lowercase		) for image in images]

        lowercase_    :Optional[Any]					    =				[to_channel_dimension_format(lowercase			,   lowercase		) for image in images]

        lowercase_    :Union[str, Any]					    =				{"pixel_values": images}
        return BatchFeature(data=lowercase			,   tensor_type=lowercase		)


