





'''simple docstring'''






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 		UpperCAmelCase (					unittest.TestCase):


  """simple docstring"""







  def __init__(					self     :       Optional[Any]				,						UpperCamelCase__     :       List[str]				,						UpperCamelCase__     :       Tuple=7				,						UpperCamelCase__     :       Optional[Any]=3				,						UpperCamelCase__     :       Optional[int]=30				,						UpperCamelCase__     :       Optional[Any]=400				,						UpperCamelCase__     :       Union[str, Any]=True				,						UpperCamelCase__     :       Any=None				,						UpperCamelCase__     :       int=True				,						UpperCamelCase__     :       List[Any]=1 / 255				,						UpperCamelCase__     :       List[Any]=True				,						UpperCamelCase__     :       Dict=[0.5, 0.5, 0.5]				,						UpperCamelCase__     :       str=[0.5, 0.5, 0.5]				,						UpperCamelCase__     :       Dict=True				,						)  ->    List[Any]:
    _UpperCamelCase							      =size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333}
    _UpperCamelCase							      =parent
    _UpperCamelCase							      =batch_size
    _UpperCamelCase							      =num_channels
    _UpperCamelCase							      =min_resolution
    _UpperCamelCase							      =max_resolution
    _UpperCamelCase							      =do_resize
    _UpperCamelCase							      =size
    _UpperCamelCase							      =do_rescale
    _UpperCamelCase							      =rescale_factor
    _UpperCamelCase							      =do_normalize
    _UpperCamelCase							      =image_mean
    _UpperCamelCase							      =image_std
    _UpperCamelCase							      =do_pad


  def 	UpperCamelCase__   (					self     :       Optional[Any]	)  ->    Optional[Any]:
    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 	UpperCamelCase__   (					self     :       Dict				,						UpperCamelCase__     :       List[Any]				,						UpperCamelCase__     :       Any=False	)  ->    int:


    if not batched:
      _UpperCamelCase							      =image_inputs[0]
      if isinstance(UpperCamelCase__				,						Image.Image	):
        _UpperCamelCase      ,  _UpperCamelCase							      =image.size
      else:
        _UpperCamelCase      ,  _UpperCamelCase							      =image.shape[1], image.shape[2]
      if w < h:
        _UpperCamelCase							      =int(self.size['''shortest_edge'''] * h / w	)
        _UpperCamelCase							      =self.size['''shortest_edge''']
      elif w > h:
        _UpperCamelCase							      =self.size['''shortest_edge''']
        _UpperCamelCase							      =int(self.size['''shortest_edge'''] * w / h	)
      else:
        _UpperCamelCase							      =self.size['''shortest_edge''']
        _UpperCamelCase							      =self.size['''shortest_edge''']

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

    return expected_height, expected_width







@require_torch
@require_vision
class 		UpperCAmelCase (					lowercase_ ,  unittest.TestCase):


  """simple docstring"""







  lowerCAmelCase_											=					DetrImageProcessor if is_vision_available() else None


  def 	UpperCamelCase__   (					self     :       List[str]	)  ->    List[str]:
    _UpperCamelCase							      =DetrImageProcessingTester(self	)


  @property
  def 	UpperCamelCase__   (					self     :       List[Any]	)  ->    Dict:
    return self.image_processor_tester.prepare_image_processor_dict()


  def 	UpperCamelCase__   (					self     :       Tuple	)  ->    Dict:
    _UpperCamelCase							      =self.image_processing_class(**self.image_processor_dict	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''image_mean'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''image_std'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''do_normalize'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''do_rescale'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''rescale_factor'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''do_resize'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''size'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''do_pad'''	)	)


  def 	UpperCamelCase__   (					self     :       Dict	)  ->    Dict:
    _UpperCamelCase							      =self.image_processing_class.from_dict(self.image_processor_dict	)
    self.assertEqual(image_processor.size				,						{'''shortest_edge''': 18, '''longest_edge''': 1333}	)
    self.assertEqual(image_processor.do_pad				,						UpperCamelCase__	)

    _UpperCamelCase							      =self.image_processing_class.from_dict(
        self.image_processor_dict				,						size=42				,						max_size=84				,						pad_and_return_pixel_mask=UpperCamelCase__	)
    self.assertEqual(image_processor.size				,						{'''shortest_edge''': 42, '''longest_edge''': 84}	)
    self.assertEqual(image_processor.do_pad				,						UpperCamelCase__	)


  def 	UpperCamelCase__   (					self     :       Dict	)  ->    Tuple:
    pass


  def 	UpperCamelCase__   (					self     :       Tuple	)  ->    Any:
    _UpperCamelCase							      =self.image_processing_class(**self.image_processor_dict	)
    # create random PIL images
    _UpperCamelCase							      =prepare_image_inputs(self.image_processor_tester				,						equal_resolution=UpperCamelCase__	)
    for image in image_inputs:
      self.assertIsInstance(UpperCamelCase__				,						Image.Image	)

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

    _UpperCamelCase      ,  _UpperCamelCase							      =self.image_processor_tester.get_expected_values(UpperCamelCase__	)

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

    # Test batched
    _UpperCamelCase      ,  _UpperCamelCase							      =self.image_processor_tester.get_expected_values(UpperCamelCase__				,						batched=UpperCamelCase__	)

    _UpperCamelCase							      =image_processing(UpperCamelCase__				,						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 	UpperCamelCase__   (					self     :       Tuple	)  ->    Dict:
    _UpperCamelCase							      =self.image_processing_class(**self.image_processor_dict	)
    # create random numpy tensors
    _UpperCamelCase							      =prepare_image_inputs(self.image_processor_tester				,						equal_resolution=UpperCamelCase__				,						numpify=UpperCamelCase__	)
    for image in image_inputs:
      self.assertIsInstance(UpperCamelCase__				,						np.ndarray	)

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

    _UpperCamelCase      ,  _UpperCamelCase							      =self.image_processor_tester.get_expected_values(UpperCamelCase__	)

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

    # Test batched
    _UpperCamelCase							      =image_processing(UpperCamelCase__				,						return_tensors='''pt'''	).pixel_values

    _UpperCamelCase      ,  _UpperCamelCase							      =self.image_processor_tester.get_expected_values(UpperCamelCase__				,						batched=UpperCamelCase__	)

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


  def 	UpperCamelCase__   (					self     :       Union[str, Any]	)  ->    Optional[Any]:
    _UpperCamelCase							      =self.image_processing_class(**self.image_processor_dict	)
    # create random PyTorch tensors
    _UpperCamelCase							      =prepare_image_inputs(self.image_processor_tester				,						equal_resolution=UpperCamelCase__				,						torchify=UpperCamelCase__	)
    for image in image_inputs:
      self.assertIsInstance(UpperCamelCase__				,						torch.Tensor	)

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

    _UpperCamelCase      ,  _UpperCamelCase							      =self.image_processor_tester.get_expected_values(UpperCamelCase__	)

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

    # Test batched
    _UpperCamelCase							      =image_processing(UpperCamelCase__				,						return_tensors='''pt'''	).pixel_values

    _UpperCamelCase      ,  _UpperCamelCase							      =self.image_processor_tester.get_expected_values(UpperCamelCase__				,						batched=UpperCamelCase__	)

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


  @slow
  def 	UpperCamelCase__   (					self     :       str	)  ->    str:
    _UpperCamelCase							      =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt'''				,						'''r'''	) as f:
      _UpperCamelCase							      =json.loads(f.read()	)

    _UpperCamelCase							      ={'''image_id''': 3_9769, '''annotations''': target}

    # encode them
    _UpperCamelCase							      =DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50'''	)
    _UpperCamelCase							      =image_processing(images=UpperCamelCase__				,						annotations=UpperCamelCase__				,						return_tensors='''pt'''	)

    # verify pixel values
    _UpperCamelCase							      =torch.Size([1, 3, 800, 1066]	)
    self.assertEqual(encoding['''pixel_values'''].shape				,						UpperCamelCase__	)

    _UpperCamelCase							      =torch.tensor([0.2796, 0.3138, 0.3481]	)
    self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3]				,						UpperCamelCase__				,						atol=1E-4	)	)

    # verify area
    _UpperCamelCase							      =torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area''']				,						UpperCamelCase__	)	)
    # verify boxes
    _UpperCamelCase							      =torch.Size([6, 4]	)
    self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape				,						UpperCamelCase__	)
    _UpperCamelCase							      =torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0]				,						UpperCamelCase__				,						atol=1E-3	)	)
    # verify image_id
    _UpperCamelCase							      =torch.tensor([3_9769]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id''']				,						UpperCamelCase__	)	)
    # verify is_crowd
    _UpperCamelCase							      =torch.tensor([0, 0, 0, 0, 0, 0]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd''']				,						UpperCamelCase__	)	)
    # verify class_labels
    _UpperCamelCase							      =torch.tensor([75, 75, 63, 65, 17, 17]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels''']				,						UpperCamelCase__	)	)
    # verify orig_size
    _UpperCamelCase							      =torch.tensor([480, 640]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size''']				,						UpperCamelCase__	)	)
    # verify size
    _UpperCamelCase							      =torch.tensor([800, 1066]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size''']				,						UpperCamelCase__	)	)




  @slow
  def 	UpperCamelCase__   (					self     :       Union[str, Any]	)  ->    Optional[Any]:
    _UpperCamelCase							      =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'''				,						'''r'''	) as f:
      _UpperCamelCase							      =json.loads(f.read()	)

    _UpperCamelCase							      ={'''file_name''': '''000000039769.png''', '''image_id''': 3_9769, '''segments_info''': target}

    _UpperCamelCase							      =pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic'''	)

    # encode them
    _UpperCamelCase							      =DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic'''	)
    _UpperCamelCase							      =image_processing(images=UpperCamelCase__				,						annotations=UpperCamelCase__				,						masks_path=UpperCamelCase__				,						return_tensors='''pt'''	)

    # verify pixel values
    _UpperCamelCase							      =torch.Size([1, 3, 800, 1066]	)
    self.assertEqual(encoding['''pixel_values'''].shape				,						UpperCamelCase__	)

    _UpperCamelCase							      =torch.tensor([0.2796, 0.3138, 0.3481]	)
    self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3]				,						UpperCamelCase__				,						atol=1E-4	)	)

    # verify area
    _UpperCamelCase							      =torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area''']				,						UpperCamelCase__	)	)
    # verify boxes
    _UpperCamelCase							      =torch.Size([6, 4]	)
    self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape				,						UpperCamelCase__	)
    _UpperCamelCase							      =torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0]				,						UpperCamelCase__				,						atol=1E-3	)	)
    # verify image_id
    _UpperCamelCase							      =torch.tensor([3_9769]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id''']				,						UpperCamelCase__	)	)
    # verify is_crowd
    _UpperCamelCase							      =torch.tensor([0, 0, 0, 0, 0, 0]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd''']				,						UpperCamelCase__	)	)
    # verify class_labels
    _UpperCamelCase							      =torch.tensor([17, 17, 63, 75, 75, 93]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels''']				,						UpperCamelCase__	)	)
    # verify masks
    _UpperCamelCase							      =82_2873
    self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item()				,						UpperCamelCase__	)
    # verify orig_size
    _UpperCamelCase							      =torch.tensor([480, 640]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size''']				,						UpperCamelCase__	)	)
    # verify size
    _UpperCamelCase							      =torch.tensor([800, 1066]	)
    self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size''']				,						UpperCamelCase__	)	)












'''simple docstring'''







import re
import string

import numpy as np

import datasets


lowerCAmelCase_     						=				'''
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
'''

lowerCAmelCase_     						=				'''
Args:
    predictions: List of predicted texts.
    references: List of reference texts.
    regexes_to_ignore: List, defaults to None. Regex expressions of characters to
        ignore when calculating the exact matches. Note: these regexes are removed
        from the input data before the changes based on the options below (e.g. ignore_case,
        ignore_punctuation, ignore_numbers) are applied.
    ignore_case: Boolean, defaults to False. If true, turns everything
        to lowercase so that capitalization differences are ignored.
    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
Returns:
    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results["exact_match"], 1))
    25.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results["exact_match"], 1))
    50.0


    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results["exact_match"], 1))
    75.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
    >>> print(round(results["exact_match"], 1))
    100.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]
    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results["exact_match"], 1))
    33.3

'''

lowerCAmelCase_     						=				'''
'''

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






 def 						_UpperCamelCase (self       :  Optional[Any]    )       ->   Dict:






    """simple docstring"""


    return datasets.MetricInfo(
        description=_DESCRIPTION    ,		citation=_CITATION    ,		inputs_description=_KWARGS_DESCRIPTION    ,		features=datasets.Features(
            {
                'predictions': datasets.Value('string'    ,		id='sequence'    ),
                'references': datasets.Value('string'    ,		id='sequence'    ),
            }    )    ,		reference_urls=[]    ,		)






 def 						_UpperCamelCase (self       :  List[str]    ,		a       :  str    ,		a       :  Tuple    ,		a       :  Tuple=None    ,		a       :  Dict=False    ,		a       :  Dict=False    ,		a       :  List[str]=False    ,		)       ->   int:






    """simple docstring"""


    if regexes_to_ignore is not None:
       for s in regexes_to_ignore:
          A__       =     np.array([re.sub(a    ,		''    ,		a    ) for x in predictions]    )
          A__       =     np.array([re.sub(a    ,		''    ,		a    ) for x in references]    )
    else:
       A__       =     np.asarray(a    )
       A__       =     np.asarray(a    )

    if ignore_case:
       A__       =     np.char.lower(a    )
       A__       =     np.char.lower(a    )

    if ignore_punctuation:
       A__       =     string.punctuation.maketrans(''    ,		''    ,		string.punctuation    )
       A__       =     np.char.translate(a    ,		table=a    )
       A__       =     np.char.translate(a    ,		table=a    )

    if ignore_numbers:
       A__       =     string.digits.maketrans(''    ,		''    ,		string.digits    )
       A__       =     np.char.translate(a    ,		table=a    )
       A__       =     np.char.translate(a    ,		table=a    )

    A__       =     predictions == references

    return {"exact_match": np.mean(a    ) * 1_00}


