




import argparse
import json
import re
import string
import sys
from collections import Counter
def        __lowerCAmelCase (UpperCAmelCase_		):

    def remove_articles(UpperCAmelCase_		):
        return re.sub(r"""\b(a|an|the)\b"""   ,    """ """   ,    UpperCAmelCase_		)

    def white_space_fix(UpperCAmelCase_		):
        return " ".join(text.split()		)

    def remove_punc(UpperCAmelCase_		):
        a__      =       set(string.punctuation		)
        return "".join(ch for ch in text if ch not in exclude		)

    def lower(UpperCAmelCase_		):
        return text.lower()

    return white_space_fix(remove_articles(remove_punc(lower(UpperCAmelCase_		)		)		)		)
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_		):
    a__      =       normalize_answer(UpperCAmelCase_		).split()
    a__      =       normalize_answer(UpperCAmelCase_		).split()
    a__      =       Counter(UpperCAmelCase_		) & Counter(UpperCAmelCase_		)
    a__      =       sum(common.values()		)
    if num_same == 0:
        return 0
    a__      =       1.0 * num_same / len(UpperCAmelCase_		)
    a__      =       1.0 * num_same / len(UpperCAmelCase_		)
    a__      =       (2 * precision * recall) / (precision + recall)
    return fa
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_		):
    return normalize_answer(UpperCAmelCase_		) == normalize_answer(UpperCAmelCase_		)
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_		):
    a__      =       []
    for ground_truth in ground_truths:
        a__      =       metric_fn(UpperCAmelCase_   ,    UpperCAmelCase_		)
        scores_for_ground_truths.append(UpperCAmelCase_		)
    return max(UpperCAmelCase_		)
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_		):
    a__      =       a__      =       a__      =       0
    for article in dataset:
        for paragraph in article["paragraphs"]:
            for qa in paragraph["qas"]:
                total += 1
                if qa["id"] not in predictions:
                    a__      =       """Unanswered question """ + qa["""id"""] + """ will receive score 0."""
                    print(UpperCAmelCase_   ,    file=sys.stderr		)
                    continue
                a__      =       [x["""text"""] for x in qa["""answers"""]]
                a__      =       predictions[qa["""id"""]]
                exact_match += metric_max_over_ground_truths(UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_		)
                fa += metric_max_over_ground_truths(UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_		)

    a__      =       1_0_0.0 * exact_match / total
    a__      =       1_0_0.0 * fa / total

    return {"exact_match": exact_match, "f1": fa}


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE_						:					Tuple			   =       '''1.1'''
 SCREAMING_SNAKE_CASE_						:					Optional[Any]			   =       argparse.ArgumentParser(description='''Evaluation for SQuAD ''' + expected_version)
 parser.add_argument('''dataset_file''', help='''Dataset file''')
 parser.add_argument('''prediction_file''', help='''Prediction File''')
 SCREAMING_SNAKE_CASE_						:					Union[str, Any]			   =       parser.parse_args()
 with open(args.dataset_file) as dataset_file:
  SCREAMING_SNAKE_CASE_						:					Optional[Any]			   =       json.load(dataset_file)
  if dataset_json["version"] != expected_version:
   print(
       '''Evaluation expects v-''' + expected_version + ''', but got dataset with v-''' + dataset_json['''version'''],
       file=sys.stderr,
   )
  SCREAMING_SNAKE_CASE_						:					str			   =       dataset_json['''data''']
 with open(args.prediction_file) as prediction_file:
  SCREAMING_SNAKE_CASE_						:					Tuple			   =       json.load(prediction_file)
 print(json.dumps(evaluate(dataset, predictions)))












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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import SwinaSRImageProcessor
 from transformers.image_transforms import get_image_size







class 		__UpperCAmelCase(		unittest.TestCase ):





     """simple docstring"""



     def __init__(      self :       Optional[int]						,				A :       Dict						,				A :       Union[str, Any]=7						,				A :       List[str]=3						,				A :       Optional[int]=18						,				A :       Optional[int]=30						,				A :       Optional[Any]=4_00						,				A :       Optional[Any]=True						,				A :       Tuple=1 / 2_55						,				A :       Tuple=True						,				A :       Optional[int]=8						,				)			->			Any:






         """simple docstring"""
         a__      =       parent
         a__      =       batch_size
         a__      =       num_channels
         a__      =       image_size
         a__      =       min_resolution
         a__      =       max_resolution
         a__      =       do_rescale
         a__      =       rescale_factor
         a__      =       do_pad
         a__      =       pad_size

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]    )			->			Union[str, Any]:






         """simple docstring"""
         return {
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_pad": self.do_pad,
             "pad_size": self.pad_size,
         }






     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       int=False						,				A :       Any=False						,				A :       List[Any]=False    )			->			Optional[Any]:






         """simple docstring"""
         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

         if equal_resolution:
             a__      =       []
             for i in range(self.batch_size    ):
                 image_inputs.append(
                     np.random.randint(
                         2_55						,				size=(self.num_channels, self.max_resolution, self.max_resolution)						,				dtype=np.uinta    )    )
         else:
             a__      =       []
             for i in range(self.batch_size    ):
                 a__ ,		a__      =       np.random.choice(np.arange(self.min_resolution						,				self.max_resolution    )						,				2    )
                 image_inputs.append(np.random.randint(2_55						,				size=(self.num_channels, width, height)						,				dtype=np.uinta    )    )

         if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             a__      =       [Image.fromarray(np.moveaxis(A						,				0						,				-1    )    ) for x in image_inputs]

         if torchify:
             a__      =       [torch.from_numpy(A    ) for x in image_inputs]

         return image_inputs







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





     """simple docstring"""



     __UpperCAmelCase	: Dict						=    SwinaSRImageProcessor if is_vision_available() else None

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			Dict:






         """simple docstring"""
         a__      =       SwinaSRImageProcessingTester(self    )

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]    )			->			List[Any]:






         """simple docstring"""
         return self.image_processor_tester.prepare_image_processor_dict()

     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			int:






         """simple docstring"""
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         self.assertTrue(hasattr(A						,				"""do_rescale"""    )    )
         self.assertTrue(hasattr(A						,				"""rescale_factor"""    )    )
         self.assertTrue(hasattr(A						,				"""do_pad"""    )    )
         self.assertTrue(hasattr(A						,				"""pad_size"""    )    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			List[Any]:






         """simple docstring"""
         pass

     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       Optional[Any]    )			->			List[str]:






         """simple docstring"""
         a__ ,		a__      =       get_image_size(A    )
         a__      =       self.image_processor_tester.pad_size

         a__      =       (old_height // size + 1) * size - old_height
         a__      =       (old_width // size + 1) * size - old_width
         return old_height + pad_height, old_width + pad_width

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






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random PIL images
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				Image.Image    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(np.array(image_inputs[0]    )    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Optional[Any]:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random numpy tensors
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A						,				numpify=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				np.ndarray    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(image_inputs[0]    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)






     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Tuple:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random PyTorch tensors
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A						,				torchify=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				torch.Tensor    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(image_inputs[0]    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)






