
from sklearn.metrics import fa_score

import datasets


__magic_name__  							=	'''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


__magic_name__  							=	'''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. 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.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

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

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

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_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(round(results[\'f1\'], 2))
        0.35

    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 = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


__magic_name__  							=	'''
@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        _SCREAMING_SNAKE_CASE	(   datasets.Metric			):
      def A_      (      self			):
          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.f1_score.html"]		,						)



      def A_      (      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase=None		,						lowerCamelCase=1		,						lowerCamelCase="binary"		,						lowerCamelCase=None			):
          snake_case__    =					fa_score(
              lowerCamelCase		,						lowerCamelCase		,						labels=lowerCamelCase		,						pos_label=lowerCamelCase		,						average=lowerCamelCase		,						sample_weight=lowerCamelCase			)
          return {"f1": float(lowerCamelCase			) if score.size == 1 else score}





import json
import pathlib
import unittest

import numpy as np

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

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import DetrImageProcessor




class        _SCREAMING_SNAKE_CASE	(   unittest.TestCase			):
      def __init__(      self		,						lowerCamelCase		,						lowerCamelCase=7		,						lowerCamelCase=3		,						lowerCamelCase=30		,						lowerCamelCase=4_00		,						lowerCamelCase=True		,						lowerCamelCase=None		,						lowerCamelCase=True		,						lowerCamelCase=1 / 2_55		,						lowerCamelCase=True		,						lowerCamelCase=[0.5, 0.5, 0.5]		,						lowerCamelCase=[0.5, 0.5, 0.5]		,						lowerCamelCase=True		,						):
          # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
          snake_case__    =					size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33}
          snake_case__    =					parent
          snake_case__    =					batch_size
          snake_case__    =					num_channels
          snake_case__    =					min_resolution
          snake_case__    =					max_resolution
          snake_case__    =					do_resize
          snake_case__    =					size
          snake_case__    =					do_rescale
          snake_case__    =					rescale_factor
          snake_case__    =					do_normalize
          snake_case__    =					image_mean
          snake_case__    =					image_std
          snake_case__    =					do_pad
      def A_      (      self			):
          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_rescale": self.do_rescale,
              "rescale_factor": self.rescale_factor,
              "do_normalize": self.do_normalize,
              "image_mean": self.image_mean,
              "image_std": self.image_std,
              "do_pad": self.do_pad,
          }



      def A_      (      self		,						lowerCamelCase		,						lowerCamelCase=False			):
          if not batched:
              snake_case__    =					image_inputs[0]
              if isinstance(lowerCamelCase		,						Image.Image			):
                  snake_case__    ,       snake_case__    =					image.size
              else:
                  snake_case__    ,       snake_case__    =					image.shape[1], image.shape[2]
              if w < h:
                  snake_case__    =					int(self.size["shortest_edge"] * h / w			)
                  snake_case__    =					self.size["shortest_edge"]
              elif w > h:
                  snake_case__    =					self.size["shortest_edge"]
                  snake_case__    =					int(self.size["shortest_edge"] * w / h			)
              else:
                  snake_case__    =					self.size["shortest_edge"]
                  snake_case__    =					self.size["shortest_edge"]

          else:
              snake_case__    =					[]
              for image in image_inputs:
                  snake_case__    ,       snake_case__    =					self.get_expected_values([image]			)
                  expected_values.append((expected_height, expected_width)			)
              snake_case__    =					max(lowerCamelCase		,						key=lambda lowerCamelCase			: item[0]			)[0]
              snake_case__    =					max(lowerCamelCase		,						key=lambda lowerCamelCase			: item[1]			)[1]

          return expected_height, expected_width





@require_torch
@require_vision
class        _SCREAMING_SNAKE_CASE	(   __UpperCamelCase							,       unittest.TestCase			):
      _A    :		Optional[Any]     						=  DetrImageProcessor if is_vision_available() else None
      def A_      (      self			):
          snake_case__    =					DetrImageProcessingTester(self			)
      @property
      def A_      (      self			):
          return self.image_processor_tester.prepare_image_processor_dict()
      def A_      (      self			):
          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_rescale"			)			)
          self.assertTrue(hasattr(lowerCamelCase		,						"rescale_factor"			)			)
          self.assertTrue(hasattr(lowerCamelCase		,						"do_resize"			)			)
          self.assertTrue(hasattr(lowerCamelCase		,						"size"			)			)
          self.assertTrue(hasattr(lowerCamelCase		,						"do_pad"			)			)
      def A_      (      self			):
          snake_case__    =					self.image_processing_class.from_dict(self.image_processor_dict			)
          self.assertEqual(image_processor.size		,						{"shortest_edge": 18, "longest_edge": 13_33}			)
          self.assertEqual(image_processor.do_pad		,						lowerCamelCase			)

          snake_case__    =					self.image_processing_class.from_dict(
              self.image_processor_dict		,						size=42		,						max_size=84		,						pad_and_return_pixel_mask=lowerCamelCase			)
          self.assertEqual(image_processor.size		,						{"shortest_edge": 42, "longest_edge": 84}			)
          self.assertEqual(image_processor.do_pad		,						lowerCamelCase			)
      def A_      (      self			):
          pass
      def A_      (      self			):
          # Initialize image_processing
          snake_case__    =					self.image_processing_class(**self.image_processor_dict			)
          # create random PIL images
          snake_case__    =					prepare_image_inputs(self.image_processor_tester		,						equal_resolution=lowerCamelCase			)
          for image in image_inputs:
              self.assertIsInstance(lowerCamelCase		,						Image.Image			)

          # Test not batched input
          snake_case__    =					image_processing(image_inputs[0]		,						return_tensors="pt"			).pixel_values

          snake_case__    ,       snake_case__    =					self.image_processor_tester.get_expected_values(lowerCamelCase			)

          self.assertEqual(
              encoded_images.shape		,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,						)

          # Test batched
          snake_case__    ,       snake_case__    =					self.image_processor_tester.get_expected_values(lowerCamelCase		,						batched=lowerCamelCase			)

          snake_case__    =					image_processing(lowerCamelCase		,						return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape		,						(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              )		,						)
      def A_      (      self			):
          # Initialize image_processing
          snake_case__    =					self.image_processing_class(**self.image_processor_dict			)
          # create random numpy tensors
          snake_case__    =					prepare_image_inputs(self.image_processor_tester		,						equal_resolution=lowerCamelCase		,						numpify=lowerCamelCase			)
          for image in image_inputs:
              self.assertIsInstance(lowerCamelCase		,						np.ndarray			)

          # Test not batched input
          snake_case__    =					image_processing(image_inputs[0]		,						return_tensors="pt"			).pixel_values

          snake_case__    ,       snake_case__    =					self.image_processor_tester.get_expected_values(lowerCamelCase			)

          self.assertEqual(
              encoded_images.shape		,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,						)

          # Test batched
          snake_case__    =					image_processing(lowerCamelCase		,						return_tensors="pt"			).pixel_values

          snake_case__    ,       snake_case__    =					self.image_processor_tester.get_expected_values(lowerCamelCase		,						batched=lowerCamelCase			)

          self.assertEqual(
              encoded_images.shape		,						(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              )		,						)
      def A_      (      self			):
          # Initialize image_processing
          snake_case__    =					self.image_processing_class(**self.image_processor_dict			)
          # create random PyTorch tensors
          snake_case__    =					prepare_image_inputs(self.image_processor_tester		,						equal_resolution=lowerCamelCase		,						torchify=lowerCamelCase			)
          for image in image_inputs:
              self.assertIsInstance(lowerCamelCase		,						torch.Tensor			)

          # Test not batched input
          snake_case__    =					image_processing(image_inputs[0]		,						return_tensors="pt"			).pixel_values

          snake_case__    ,       snake_case__    =					self.image_processor_tester.get_expected_values(lowerCamelCase			)

          self.assertEqual(
              encoded_images.shape		,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,						)

          # Test batched
          snake_case__    =					image_processing(lowerCamelCase		,						return_tensors="pt"			).pixel_values

          snake_case__    ,       snake_case__    =					self.image_processor_tester.get_expected_values(lowerCamelCase		,						batched=lowerCamelCase			)

          self.assertEqual(
              encoded_images.shape		,						(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              )		,						)
      @slow
      def A_      (      self			):
          # prepare image and target
          snake_case__    =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
          with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"		,						"r"			) as f:
              snake_case__    =					json.loads(f.read()			)

          snake_case__    =					{"image_id": 3_97_69, "annotations": target}

          # encode them
          snake_case__    =					DetrImageProcessor.from_pretrained("facebook/detr-resnet-50"			)
          snake_case__    =					image_processing(images=lowerCamelCase		,						annotations=lowerCamelCase		,						return_tensors="pt"			)

          # verify pixel values
          snake_case__    =					torch.Size([1, 3, 8_00, 10_66]			)
          self.assertEqual(encoding["pixel_values"].shape		,						lowerCamelCase			)

          snake_case__    =					torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]			)
          self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]		,						lowerCamelCase		,						atol=1e-4			)			)

          # verify area
          snake_case__    =					torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["area"]		,						lowerCamelCase			)			)
          # verify boxes
          snake_case__    =					torch.Size([6, 4]			)
          self.assertEqual(encoding["labels"][0]["boxes"].shape		,						lowerCamelCase			)
          snake_case__    =					torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]		,						lowerCamelCase		,						atol=1e-3			)			)
          # verify image_id
          snake_case__    =					torch.tensor([3_97_69]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]		,						lowerCamelCase			)			)
          # verify is_crowd
          snake_case__    =					torch.tensor([0, 0, 0, 0, 0, 0]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]		,						lowerCamelCase			)			)
          # verify class_labels
          snake_case__    =					torch.tensor([75, 75, 63, 65, 17, 17]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]		,						lowerCamelCase			)			)
          # verify orig_size
          snake_case__    =					torch.tensor([4_80, 6_40]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]		,						lowerCamelCase			)			)
          # verify size
          snake_case__    =					torch.tensor([8_00, 10_66]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["size"]		,						lowerCamelCase			)			)



      @slow
      def A_      (      self			):
          # prepare image, target and masks_path
          snake_case__    =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
          with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"		,						"r"			) as f:
              snake_case__    =					json.loads(f.read()			)

          snake_case__    =					{"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target}

          snake_case__    =					pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic"			)

          # encode them
          snake_case__    =					DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic"			)
          snake_case__    =					image_processing(images=lowerCamelCase		,						annotations=lowerCamelCase		,						masks_path=lowerCamelCase		,						return_tensors="pt"			)

          # verify pixel values
          snake_case__    =					torch.Size([1, 3, 8_00, 10_66]			)
          self.assertEqual(encoding["pixel_values"].shape		,						lowerCamelCase			)

          snake_case__    =					torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]			)
          self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]		,						lowerCamelCase		,						atol=1e-4			)			)

          # verify area
          snake_case__    =					torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["area"]		,						lowerCamelCase			)			)
          # verify boxes
          snake_case__    =					torch.Size([6, 4]			)
          self.assertEqual(encoding["labels"][0]["boxes"].shape		,						lowerCamelCase			)
          snake_case__    =					torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]		,						lowerCamelCase		,						atol=1e-3			)			)
          # verify image_id
          snake_case__    =					torch.tensor([3_97_69]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]		,						lowerCamelCase			)			)
          # verify is_crowd
          snake_case__    =					torch.tensor([0, 0, 0, 0, 0, 0]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]		,						lowerCamelCase			)			)
          # verify class_labels
          snake_case__    =					torch.tensor([17, 17, 63, 75, 75, 93]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]		,						lowerCamelCase			)			)
          # verify masks
          snake_case__    =					82_28_73
          self.assertEqual(encoding["labels"][0]["masks"].sum().item()		,						lowerCamelCase			)
          # verify orig_size
          snake_case__    =					torch.tensor([4_80, 6_40]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]		,						lowerCamelCase			)			)
          # verify size
          snake_case__    =					torch.tensor([8_00, 10_66]			)
          self.assertTrue(torch.allclose(encoding["labels"][0]["size"]		,						lowerCamelCase			)			)



