





from sklearn.metrics import precision_score

import datasets


SCREAMING_SNAKE_CASE_		  =			"""
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).
"""


SCREAMING_SNAKE_CASE_		  =			"""
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]
"""


SCREAMING_SNAKE_CASE_		  =			"""
@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 						UpperCamelCase__					( datasets.Metric  ):



     '''simple docstring'''

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




           '''simple docstring'''


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









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 TvltImageProcessor



def   __lowercase  ( _SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE=10					,		_SCREAMING_SNAKE_CASE=10					,		_SCREAMING_SNAKE_CASE=False					,		_SCREAMING_SNAKE_CASE=False      )					->  Optional[Any]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		[]
      for i in range(image_processor_tester.num_frames      ):
            video.append(np.random.randint(2_55					,		size=(image_processor_tester.num_channels, width, height)					,		dtype=np.uinta      )      )

      if not numpify and not torchify:
            # PIL expects the channel dimension as last dimension
            SCREAMING_SNAKE_CASE						=		[Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE					,		0					,		-1      )      ) for frame in video]

      if torchify:
            SCREAMING_SNAKE_CASE						=		[torch.from_numpy(_SCREAMING_SNAKE_CASE      ) for frame in video]

      return video



def   __lowercase  ( _SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE=False					,		_SCREAMING_SNAKE_CASE=False					,		_SCREAMING_SNAKE_CASE=False      )					->  Tuple:


      '''simple docstring'''


      assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

      SCREAMING_SNAKE_CASE						=		[]
      for i in range(image_processor_tester.batch_size      ):
            if equal_resolution:
                  SCREAMING_SNAKE_CASE						=		SCREAMING_SNAKE_CASE						=		image_processor_tester.max_resolution
            else:
                  SCREAMING_SNAKE_CASE,   SCREAMING_SNAKE_CASE						=		np.random.choice(
                      np.arange(image_processor_tester.min_resolution					,		image_processor_tester.max_resolution      )					,		2      )
                  SCREAMING_SNAKE_CASE						=		prepare_video(
                      image_processor_tester=_SCREAMING_SNAKE_CASE					,		width=_SCREAMING_SNAKE_CASE					,		height=_SCREAMING_SNAKE_CASE					,		numpify=_SCREAMING_SNAKE_CASE					,		torchify=_SCREAMING_SNAKE_CASE					,		)
            video_inputs.append(_SCREAMING_SNAKE_CASE      )

      return video_inputs

class 						UpperCamelCase__					( unittest.TestCase  ):



     '''simple docstring'''

     def __init__(				self		:       Union[str, Any]		,lowerCamelCase__		:       Tuple		,lowerCamelCase__		:       Any=7		,lowerCamelCase__		:       str=3		,lowerCamelCase__		:       Union[str, Any]=4		,lowerCamelCase__		:       Union[str, Any]=18		,lowerCamelCase__		:       Any=30		,lowerCamelCase__		:       Union[str, Any]=400		,lowerCamelCase__		:       Any=True		,lowerCamelCase__		:       Any=None		,lowerCamelCase__		:       Tuple=True		,lowerCamelCase__		:       int=[0.5, 0.5, 0.5]		,lowerCamelCase__		:       Any=[0.5, 0.5, 0.5]		,lowerCamelCase__		:       Dict=True		,lowerCamelCase__		:       Tuple=None		,)	->						Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		size if size is not None else {"""shortest_edge""": 18}
           SCREAMING_SNAKE_CASE						=		crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

           SCREAMING_SNAKE_CASE						=		parent
           SCREAMING_SNAKE_CASE						=		batch_size
           SCREAMING_SNAKE_CASE						=		num_channels
           SCREAMING_SNAKE_CASE						=		num_frames
           SCREAMING_SNAKE_CASE						=		image_size
           SCREAMING_SNAKE_CASE						=		min_resolution
           SCREAMING_SNAKE_CASE						=		max_resolution
           SCREAMING_SNAKE_CASE						=		do_resize
           SCREAMING_SNAKE_CASE						=		size
           SCREAMING_SNAKE_CASE						=		do_normalize
           SCREAMING_SNAKE_CASE						=		image_mean
           SCREAMING_SNAKE_CASE						=		image_std
           SCREAMING_SNAKE_CASE						=		do_center_crop
           SCREAMING_SNAKE_CASE						=		crop_size






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




           '''simple docstring'''


           return {
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_normalize": self.do_normalize,
               "do_resize": self.do_resize,
               "size": self.size,
               "do_center_crop": self.do_center_crop,
               "crop_size": self.crop_size,
           }

@require_torch
@require_vision
class 						UpperCamelCase__					( lowerCAmelCase_				, unittest.TestCase  ):



     '''simple docstring'''

     __snake_case       :      int						      =     TvltImageProcessor if is_vision_available() else None






     def 							SCREAMING_SNAKE_CASE__    (				self		:       Dict			)	->						Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		TvltImageProcessorTester(self			)






     @property
     def 							SCREAMING_SNAKE_CASE__    (				self		:       Optional[int]			)	->						Dict:




           '''simple docstring'''


           return self.image_processor_tester.prepare_image_processor_dict()






     def 							SCREAMING_SNAKE_CASE__    (				self		:       Any			)	->						List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		self.image_processing_class(**self.image_processor_dict			)
           self.assertTrue(hasattr(lowerCamelCase__		,"""image_mean"""			)			)
           self.assertTrue(hasattr(lowerCamelCase__		,"""image_std"""			)			)
           self.assertTrue(hasattr(lowerCamelCase__		,"""do_normalize"""			)			)
           self.assertTrue(hasattr(lowerCamelCase__		,"""do_resize"""			)			)
           self.assertTrue(hasattr(lowerCamelCase__		,"""do_center_crop"""			)			)
           self.assertTrue(hasattr(lowerCamelCase__		,"""size"""			)			)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       List[Any]			)	->						List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		self.image_processing_class(**self.image_processor_dict			)
           # create random PIL videos
           SCREAMING_SNAKE_CASE						=		prepare_video_inputs(self.image_processor_tester		,equal_resolution=lowerCamelCase__			)
           for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase__		,lowerCamelCase__			)
                 self.assertIsInstance(video[0]		,Image.Image			)

           # Test not batched input
           SCREAMING_SNAKE_CASE						=		image_processor(video_inputs[0]		,return_tensors="""pt"""			).pixel_values
           self.assertEqual(
               encoded_videos.shape		,(
                   1,
                   self.image_processor_tester.num_frames,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )		,)

           # Test batched
           SCREAMING_SNAKE_CASE						=		image_processor(lowerCamelCase__		,return_tensors="""pt"""			).pixel_values
           self.assertEqual(
               encoded_videos.shape		,(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_frames,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )		,)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       int			)	->						int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		self.image_processing_class(**self.image_processor_dict			)
           # create random numpy tensors
           SCREAMING_SNAKE_CASE						=		prepare_video_inputs(self.image_processor_tester		,equal_resolution=lowerCamelCase__		,numpify=lowerCamelCase__			)
           for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase__		,lowerCamelCase__			)
                 self.assertIsInstance(video[0]		,np.ndarray			)

           # Test not batched input
           SCREAMING_SNAKE_CASE						=		image_processor(video_inputs[0]		,return_tensors="""pt"""			).pixel_values
           self.assertEqual(
               encoded_videos.shape		,(
                   1,
                   self.image_processor_tester.num_frames,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )		,)

           # Test batched
           SCREAMING_SNAKE_CASE						=		image_processor(lowerCamelCase__		,return_tensors="""pt"""			).pixel_values
           self.assertEqual(
               encoded_videos.shape		,(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_frames,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )		,)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       str			)	->						Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		self.image_processing_class(**self.image_processor_dict			)
           # create random PyTorch tensors
           SCREAMING_SNAKE_CASE						=		prepare_video_inputs(self.image_processor_tester		,equal_resolution=lowerCamelCase__		,torchify=lowerCamelCase__			)
           for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase__		,lowerCamelCase__			)
                 self.assertIsInstance(video[0]		,torch.Tensor			)

           # Test not batched input
           SCREAMING_SNAKE_CASE						=		image_processor(video_inputs[0]		,return_tensors="""pt"""			).pixel_values
           self.assertEqual(
               encoded_videos.shape		,(
                   1,
                   self.image_processor_tester.num_frames,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )		,)

           # Test batched
           SCREAMING_SNAKE_CASE						=		image_processor(lowerCamelCase__		,return_tensors="""pt"""			).pixel_values
           self.assertEqual(
               encoded_videos.shape		,(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_frames,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )		,)


