


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







   """simple docstring"""




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




   def SCREAMING_SNAKE_CASE_   (		self				:Any							):
          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 __snake_case		(       __lowercase					,							unittest.TestCase   ):







   """simple docstring"""




   lowerCAmelCase_					: Union[str, Any]  						=      PoolFormerImageProcessor if is_vision_available() else None




   def SCREAMING_SNAKE_CASE_   (		self				:str							):
          _a							 =					PoolFormerImageProcessingTester(self							)




   @property
   def SCREAMING_SNAKE_CASE_   (		self				:List[Any]							):
          return self.image_processor_tester.prepare_image_processor_dict()




   def SCREAMING_SNAKE_CASE_   (		self				:Dict							):
          _a							 =					self.image_processing_class(**self.image_processor_dict							)
          self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,	"do_resize_and_center_crop"							)							)
          self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,	"size"							)							)
          self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,	"crop_pct"							)							)
          self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,	"do_normalize"							)							)
          self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,	"image_mean"							)							)
          self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,	"image_std"							)							)




   def SCREAMING_SNAKE_CASE_   (		self				:Dict							):
          _a							 =					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}							)

          _a							 =					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 SCREAMING_SNAKE_CASE_   (		self				:str							):
          pass




   def SCREAMING_SNAKE_CASE_   (		self				:Optional[int]							):
          _a							 =					self.image_processing_class(**self.image_processor_dict							)
          # create random PIL images
          _a							 =					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
          _a							 =					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
          _a							 =					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.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )					,	)




   def SCREAMING_SNAKE_CASE_   (		self				:Union[str, Any]							):
          _a							 =					self.image_processing_class(**self.image_processor_dict							)
          # create random numpy tensors
          _a							 =					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
          _a							 =					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
          _a							 =					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.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )					,	)




   def SCREAMING_SNAKE_CASE_   (		self				:Any							):
          _a							 =					self.image_processing_class(**self.image_processor_dict							)
          # create random PyTorch tensors
          _a							 =					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
          _a							 =					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
          _a							 =					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.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )					,	)


"""simple docstring"""




import datasets

from .evaluate import evaluate


lowerCAmelCase__				=					'\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n'

lowerCAmelCase__				=					'\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n'

lowerCAmelCase__				=					'\nComputes SQuAD scores (F1 and EM).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair as given in the references (see below)\n        - \'prediction_text\': the text of the answer\n    references: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair (see above),\n        - \'answers\': a Dict in the SQuAD dataset format\n            {\n                \'text\': list of possible texts for the answer, as a list of strings\n                \'answer_start\': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\nExamples:\n\n    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}]\n    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n    >>> squad_metric = datasets.load_metric("squad")\n    >>> results = squad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 100.0, \'f1\': 100.0}\n'





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

							def _lowercase       (self     ):

									"""simple docstring"""







									return datasets.MetricInfo(
									    description=_DESCRIPTION							,							citation=_CITATION							,							inputs_description=_KWARGS_DESCRIPTION							,							features=datasets.Features(
									        {
									            '''predictions''': {'''id''': datasets.Value('''string'''     ), '''prediction_text''': datasets.Value('''string'''     )},
									            '''references''': {
									                '''id''': datasets.Value('''string'''     ),
									                '''answers''': datasets.features.Sequence(
									                    {
									                        '''text''': datasets.Value('''string'''     ),
									                        '''answer_start''': datasets.Value('''int32'''     ),
									                    }     ),
									            },
									        }     )							,							codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/''']							,							reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/''']							,							)







							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			{prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
									SCREAMING_SNAKE_CASE_    			=			[
									    {
									        '''paragraphs''': [
									            {
									                '''qas''': [
									                    {
									                        '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
									                        '''id''': ref['''id'''],
									                    }
									                    for ref in references
									                ]
									            }
									        ]
									    }
									]
									SCREAMING_SNAKE_CASE_    			=			evaluate(dataset=SCREAMING_SNAKE_CASE_							,							predictions=SCREAMING_SNAKE_CASE_     )
									return score