

'''simple docstring'''

import re
import string

import numpy as np

import datasets


lowercase__         =      "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n"

lowercase__         =      "\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    33.3\n\n"

lowercase__         =      "\n"




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






     '''simple docstring'''



     def        UpperCAmelCase_	(		self			:					Optional[int]	)						->     List[str]:
      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			:					str					,      lowercase_			:					Optional[int]					,      lowercase_			:					Optional[Any]					,      lowercase_			:					Optional[int]=None					,      lowercase_			:					Tuple=False					,      lowercase_			:					List[str]=False					,      lowercase_			:					Optional[int]=False					,      )						->     Union[str, Any]:
      if regexes_to_ignore is not None:
       for s in regexes_to_ignore:
        UpperCAmelCase	:     int						 =			np.array([re.sub(lowercase_					,      ''					,      lowercase_	) for x in predictions]	)
        UpperCAmelCase	:     Optional[Any]						 =			np.array([re.sub(lowercase_					,      ''					,      lowercase_	) for x in references]	)
      else:
       UpperCAmelCase	:     Optional[int]						 =			np.asarray(lowercase_	)
       UpperCAmelCase	:     Union[str, Any]						 =			np.asarray(lowercase_	)

      if ignore_case:
       UpperCAmelCase	:     str						 =			np.char.lower(lowercase_	)
       UpperCAmelCase	:     Dict						 =			np.char.lower(lowercase_	)

      if ignore_punctuation:
       UpperCAmelCase	:     str						 =			string.punctuation.maketrans(''					,      ''					,      string.punctuation	)
       UpperCAmelCase	:     Union[str, Any]						 =			np.char.translate(lowercase_					,      table=lowercase_	)
       UpperCAmelCase	:     Optional[int]						 =			np.char.translate(lowercase_					,      table=lowercase_	)

      if ignore_numbers:
       UpperCAmelCase	:     Optional[Any]						 =			string.digits.maketrans(''					,      ''					,      string.digits	)
       UpperCAmelCase	:     Tuple						 =			np.char.translate(lowercase_					,      table=lowercase_	)
       UpperCAmelCase	:     Any						 =			np.char.translate(lowercase_					,      table=lowercase_	)

      UpperCAmelCase	:     Union[str, Any]						 =			predictions == references

      return {"exact_match": np.mean(lowercase_	) * 100}







'''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, prepare_image_inputs


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import PoolFormerImageProcessor




class 	A_			(    unittest.TestCase							):






     '''simple docstring'''



     def __init__(		self			:					Any					,      lowercase_			:					str					,      lowercase_			:					Union[str, Any]=7					,      lowercase_			:					Union[str, Any]=3					,      lowercase_			:					int=30					,      lowercase_			:					Tuple=400					,      lowercase_			:					Tuple=True					,      lowercase_			:					Optional[int]=None					,      lowercase_			:					List[str]=0.9					,      lowercase_			:					Tuple=None					,      lowercase_			:					Union[str, Any]=True					,      lowercase_			:					int=[0.5, 0.5, 0.5]					,      lowercase_			:					List[str]=[0.5, 0.5, 0.5]					,      )						->     Tuple:
      UpperCAmelCase	:     Optional[int]						 =			size if size is not None else {'shortest_edge': 30}
      UpperCAmelCase	:     int						 =			crop_size if crop_size is not None else {'height': 30, 'width': 30}
      UpperCAmelCase	:     Tuple						 =			parent
      UpperCAmelCase	:     Optional[Any]						 =			batch_size
      UpperCAmelCase	:     int						 =			num_channels
      UpperCAmelCase	:     int						 =			min_resolution
      UpperCAmelCase	:     Optional[int]						 =			max_resolution
      UpperCAmelCase	:     str						 =			do_resize_and_center_crop
      UpperCAmelCase	:     int						 =			size
      UpperCAmelCase	:     Dict						 =			crop_pct
      UpperCAmelCase	:     Union[str, Any]						 =			crop_size
      UpperCAmelCase	:     Optional[int]						 =			do_normalize
      UpperCAmelCase	:     Optional[Any]						 =			image_mean
      UpperCAmelCase	:     Optional[Any]						 =			image_std




     def        UpperCAmelCase_	(		self			:					str	)						->     int:
      return {
          "size": self.size,
          "do_resize_and_center_crop": self.do_resize_and_center_crop,
          "crop_pct": self.crop_pct,
          "crop_size": self.crop_size,
          "do_normalize": self.do_normalize,
          "image_mean": self.image_mean,
          "image_std": self.image_std,
      }




@require_torch
@require_vision
class 	A_			(    _snake_case	,       unittest.TestCase							):






     '''simple docstring'''



     UpperCAmelCase_						:     Tuple  		=  PoolFormerImageProcessor if is_vision_available() else None


     def        UpperCAmelCase_	(		self			:					Dict	)						->     str:
      UpperCAmelCase	:     Any						 =			PoolFormerImageProcessingTester(self	)


     @property
     def        UpperCAmelCase_	(		self			:					List[Any]	)						->     Union[str, Any]:
      return self.image_processor_tester.prepare_image_processor_dict()


     def        UpperCAmelCase_	(		self			:					Tuple	)						->     str:
      UpperCAmelCase	:     Any						 =			self.image_processing_class(**self.image_processor_dict	)
      self.assertTrue(hasattr(lowercase_					,      'do_resize_and_center_crop'	)	)
      self.assertTrue(hasattr(lowercase_					,      'size'	)	)
      self.assertTrue(hasattr(lowercase_					,      'crop_pct'	)	)
      self.assertTrue(hasattr(lowercase_					,      'do_normalize'	)	)
      self.assertTrue(hasattr(lowercase_					,      'image_mean'	)	)
      self.assertTrue(hasattr(lowercase_					,      'image_std'	)	)


     def        UpperCAmelCase_	(		self			:					Optional[Any]	)						->     Tuple:
      UpperCAmelCase	:     List[str]						 =			self.image_processing_class.from_dict(self.image_processor_dict	)
      self.assertEqual(image_processor.size					,      {'shortest_edge': 30}	)
      self.assertEqual(image_processor.crop_size					,      {'height': 30, 'width': 30}	)

      UpperCAmelCase	:     Any						 =			self.image_processing_class.from_dict(self.image_processor_dict					,      size=42					,      crop_size=84	)
      self.assertEqual(image_processor.size					,      {'shortest_edge': 42}	)
      self.assertEqual(image_processor.crop_size					,      {'height': 84, 'width': 84}	)


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


     def        UpperCAmelCase_	(		self			:					List[Any]	)						->     List[str]:
      # Initialize image_processing
      UpperCAmelCase	:     int						 =			self.image_processing_class(**self.image_processor_dict	)
      # create random PIL images
      UpperCAmelCase	:     Any						 =			prepare_image_inputs(self.image_processor_tester					,      equal_resolution=lowercase_	)
      for image in image_inputs:
       self.assertIsInstance(lowercase_					,      Image.Image	)

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

      self.assertEqual(
          encoded_images.shape					,      (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )					,      )

      # Test batched
      UpperCAmelCase	:     str						 =			image_processing(lowercase_					,      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.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )					,      )


     def        UpperCAmelCase_	(		self			:					List[Any]	)						->     Dict:
      # Initialize image_processing
      UpperCAmelCase	:     int						 =			self.image_processing_class(**self.image_processor_dict	)
      # create random numpy tensors
      UpperCAmelCase	:     Dict						 =			prepare_image_inputs(self.image_processor_tester					,      equal_resolution=lowercase_					,      numpify=lowercase_	)
      for image in image_inputs:
       self.assertIsInstance(lowercase_					,      np.ndarray	)

      # Test not batched input
      UpperCAmelCase	:     Optional[Any]						 =			image_processing(image_inputs[0]					,      return_tensors='pt'	).pixel_values
      self.assertEqual(
          encoded_images.shape					,      (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )					,      )

      # Test batched
      UpperCAmelCase	:     Optional[Any]						 =			image_processing(lowercase_					,      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.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )					,      )




     def        UpperCAmelCase_	(		self			:					str	)						->     Dict:
      # Initialize image_processing
      UpperCAmelCase	:     Optional[Any]						 =			self.image_processing_class(**self.image_processor_dict	)
      # create random PyTorch tensors
      UpperCAmelCase	:     Tuple						 =			prepare_image_inputs(self.image_processor_tester					,      equal_resolution=lowercase_					,      torchify=lowercase_	)
      for image in image_inputs:
       self.assertIsInstance(lowercase_					,      torch.Tensor	)

      # Test not batched input
      UpperCAmelCase	:     int						 =			image_processing(image_inputs[0]					,      return_tensors='pt'	).pixel_values
      self.assertEqual(
          encoded_images.shape					,      (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )					,      )

      # Test batched
      UpperCAmelCase	:     Optional[int]						 =			image_processing(lowercase_					,      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.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )					,      )




