





'''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 LevitImageProcessor







class 		UpperCAmelCase (					unittest.TestCase):


  """simple docstring"""







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




  def 	UpperCamelCase__   (					self     :       Dict	)  ->    str:
    return {
        "image_mean": self.image_mean,
        "image_std": self.image_std,
        "do_normalize": self.do_normalize,
        "do_resize": self.do_resize,
        "do_center_crop": self.do_center_crop,
        "size": self.size,
        "crop_size": self.crop_size,
    }







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


  """simple docstring"""







  lowerCAmelCase_											=					LevitImageProcessor if is_vision_available() else None


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


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


  def 	UpperCamelCase__   (					self     :       Tuple	)  ->    Any:
    _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_resize'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''do_center_crop'''	)	)
    self.assertTrue(hasattr(UpperCamelCase__				,						'''size'''	)	)


  def 	UpperCamelCase__   (					self     :       int	)  ->    Tuple:
    _UpperCamelCase							      =self.image_processing_class.from_dict(self.image_processor_dict	)
    self.assertEqual(image_processor.size				,						{'''shortest_edge''': 18}	)
    self.assertEqual(image_processor.crop_size				,						{'''height''': 18, '''width''': 18}	)

    _UpperCamelCase							      =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     :       List[Any]	)  ->    int:
    pass


  def 	UpperCamelCase__   (					self     :       Any	)  ->    Optional[int]:
    _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
    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							      =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,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )				,						)


  def 	UpperCamelCase__   (					self     :       Optional[Any]	)  ->    Tuple:
    _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
    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							      =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,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )				,						)




  def 	UpperCamelCase__   (					self     :       Tuple	)  ->    str:
    _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
    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							      =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,
            self.image_processor_tester.crop_size['''height'''],
            self.image_processor_tester.crop_size['''width'''],
        )				,						)












'''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}


