
import unittest

import numpy as np

from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision

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 DPTImageProcessor
class  lowercase__(				unittest.TestCase							):



	"""simple docstring"""




	def __init__(       self  :			str       ,							SCREAMING_SNAKE_CASE_  :			Optional[Any]       ,							SCREAMING_SNAKE_CASE_  :			Optional[Any]=7       ,							SCREAMING_SNAKE_CASE_  :			Optional[int]=3       ,							SCREAMING_SNAKE_CASE_  :			Any=1_8       ,							SCREAMING_SNAKE_CASE_  :			Tuple=3_0       ,							SCREAMING_SNAKE_CASE_  :			int=4_0_0       ,							SCREAMING_SNAKE_CASE_  :			Dict=True       ,							SCREAMING_SNAKE_CASE_  :			str=None       ,							SCREAMING_SNAKE_CASE_  :			Any=True       ,							SCREAMING_SNAKE_CASE_  :			Optional[Any]=[0.5, 0.5, 0.5]       ,							SCREAMING_SNAKE_CASE_  :			List[str]=[0.5, 0.5, 0.5]       ,							)       ->     Optional[Any]:
					lowercase_       =					size if size is not None else {'''height''': 1_8, '''width''': 1_8}
					lowercase_       =					parent
					lowercase_       =					batch_size
					lowercase_       =					num_channels
					lowercase_       =					image_size
					lowercase_       =					min_resolution
					lowercase_       =					max_resolution
					lowercase_       =					do_resize
					lowercase_       =					size
					lowercase_       =					do_normalize
					lowercase_       =					image_mean
					lowercase_       =					image_std




	def 						_lowercase  (       self  :			Tuple       )       ->     List[Any]:
					return {
					    "image_mean": self.image_mean,
					    "image_std": self.image_std,
					    "do_normalize": self.do_normalize,
					    "do_resize": self.do_resize,
					    "size": self.size,
					}

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



	"""simple docstring"""




	a			:Optional[Any]         =	DPTImageProcessor if is_vision_available() else None
	def 						_lowercase  (       self  :			Any       )       ->     Union[str, Any]:
					lowercase_       =					DPTImageProcessingTester(self       )
	@property
	def 						_lowercase  (       self  :			Any       )       ->     Optional[int]:
					return self.image_processor_tester.prepare_image_processor_dict()
	def 						_lowercase  (       self  :			int       )       ->     Dict:
					lowercase_       =					self.image_processing_class(**self.image_processor_dict       )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,							'''image_mean'''       )       )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,							'''image_std'''       )       )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,							'''do_normalize'''       )       )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,							'''do_resize'''       )       )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,							'''size'''       )       )
	def 						_lowercase  (       self  :			Optional[Any]       )       ->     Optional[int]:
					lowercase_       =					self.image_processing_class.from_dict(self.image_processor_dict       )
					self.assertEqual(image_processor.size       ,							{'''height''': 1_8, '''width''': 1_8}       )

					lowercase_       =					self.image_processing_class.from_dict(self.image_processor_dict       ,							size=4_2       )
					self.assertEqual(image_processor.size       ,							{'''height''': 4_2, '''width''': 4_2}       )
	def 						_lowercase  (       self  :			Tuple       )       ->     List[Any]:
					# Initialize image_processing
					lowercase_       =					self.image_processing_class(**self.image_processor_dict       )
					# create random PIL images
					lowercase_       =					prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=SCREAMING_SNAKE_CASE_       )
					for image in image_inputs:
									self.assertIsInstance(SCREAMING_SNAKE_CASE_       ,							Image.Image       )

					# Test not batched input
					lowercase_       =					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.size['''height'''],
					        self.image_processor_tester.size['''width'''],
					    )       ,							)

					# Test batched
					lowercase_       =					image_processing(SCREAMING_SNAKE_CASE_       ,							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.size['''height'''],
					        self.image_processor_tester.size['''width'''],
					    )       ,							)
	def 						_lowercase  (       self  :			str       )       ->     Optional[int]:
					# Initialize image_processing
					lowercase_       =					self.image_processing_class(**self.image_processor_dict       )
					# create random numpy tensors
					lowercase_       =					prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=SCREAMING_SNAKE_CASE_       ,							numpify=SCREAMING_SNAKE_CASE_       )
					for image in image_inputs:
									self.assertIsInstance(SCREAMING_SNAKE_CASE_       ,							np.ndarray       )

					# Test not batched input
					lowercase_       =					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.size['''height'''],
					        self.image_processor_tester.size['''width'''],
					    )       ,							)

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




	def 						_lowercase  (       self  :			List[str]       )       ->     str:
					# Initialize image_processing
					lowercase_       =					self.image_processing_class(**self.image_processor_dict       )
					# create random PyTorch tensors
					lowercase_       =					prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=SCREAMING_SNAKE_CASE_       ,							torchify=SCREAMING_SNAKE_CASE_       )
					for image in image_inputs:
									self.assertIsInstance(SCREAMING_SNAKE_CASE_       ,							torch.Tensor       )

					# Test not batched input
					lowercase_       =					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.size['''height'''],
					        self.image_processor_tester.size['''width'''],
					    )       ,							)

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












import re
import string

import numpy as np

import datasets


UpperCAmelCase_ :						Dict      =      '''
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.
'''

UpperCAmelCase_ :						Any      =      '''
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

'''

UpperCAmelCase_ :						Tuple      =      '''
'''

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





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

		if ignore_case:
			UpperCamelCase     :Tuple          =	np.char.lower(__lowerCamelCase	)
			UpperCamelCase     :Any          =	np.char.lower(__lowerCamelCase	)

		if ignore_punctuation:
			UpperCamelCase     :Optional[int]          =	string.punctuation.maketrans("""""" ,  """""" ,  string.punctuation	)
			UpperCamelCase     :Optional[Any]          =	np.char.translate(__lowerCamelCase ,  table=__lowerCamelCase	)
			UpperCamelCase     :List[str]          =	np.char.translate(__lowerCamelCase ,  table=__lowerCamelCase	)

		if ignore_numbers:
			UpperCamelCase     :Tuple          =	string.digits.maketrans("""""" ,  """""" ,  string.digits	)
			UpperCamelCase     :Dict          =	np.char.translate(__lowerCamelCase ,  table=__lowerCamelCase	)
			UpperCamelCase     :Tuple          =	np.char.translate(__lowerCamelCase ,  table=__lowerCamelCase	)

		UpperCamelCase     :int          =	predictions == references

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