


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 MobileViTImageProcessor


class 					lowerCAmelCase_ (       unittest.TestCase):




						def __init__(	self						:   Union[str, Any]   ,     __A						:   Optional[Any]   ,     __A						:   str=7   ,     __A						:   List[Any]=3   ,     __A						:   int=18   ,     __A						:   Optional[Any]=30   ,     __A						:   List[Any]=400   ,     __A						:   Any=True   ,     __A						:   Union[str, Any]=None   ,     __A						:   List[Any]=True   ,     __A						:   Any=None   ,     __A						:   int=True   ,     )      ->Optional[int]:






									"""simple docstring"""






									a__ :str						  =    size if size is not None else {"shortest_edge": 20}
									a__ :Any						  =    crop_size if crop_size is not None else {"height": 18, "width": 18}
									a__ :str						  =    parent
									a__ :int						  =    batch_size
									a__ :List[Any]						  =    num_channels
									a__ :List[str]						  =    image_size
									a__ :Dict						  =    min_resolution
									a__ :str						  =    max_resolution
									a__ :List[Any]						  =    do_resize
									a__ :Any						  =    size
									a__ :Any						  =    do_center_crop
									a__ :Any						  =    crop_size
									a__ :List[str]						  =    do_flip_channel_order






						def  _snake_case					(	self						:   int						)      ->List[Any]:






									"""simple docstring"""






									return {
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "do_center_crop": self.do_center_crop,
									    "crop_size": self.crop_size,
									    "do_flip_channel_order": self.do_flip_channel_order,
									}






@require_torch
@require_vision
class 					lowerCAmelCase_ (       _a			,unittest.TestCase):
						lowerCamelCase_         =     MobileViTImageProcessor if is_vision_available() else None




						def  _snake_case					(	self						:   Tuple						)      ->Optional[int]:






									"""simple docstring"""






									a__ :List[Any]						  =    MobileViTImageProcessingTester(self						)




						@property
						def  _snake_case					(	self						:   List[Any]						)      ->Union[str, Any]:






									"""simple docstring"""






									return self.image_processor_tester.prepare_image_processor_dict()




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






									"""simple docstring"""






									a__ :Any						  =    self.image_processing_class(**self.image_processor_dict						)
									self.assertTrue(hasattr(__A   ,     "do_resize"						)						)
									self.assertTrue(hasattr(__A   ,     "size"						)						)
									self.assertTrue(hasattr(__A   ,     "do_center_crop"						)						)
									self.assertTrue(hasattr(__A   ,     "center_crop"						)						)
									self.assertTrue(hasattr(__A   ,     "do_flip_channel_order"						)						)




						def  _snake_case					(	self						:   str						)      ->List[Any]:






									"""simple docstring"""






									a__ :str						  =    self.image_processing_class.from_dict(self.image_processor_dict						)
									self.assertEqual(image_processor.size   ,     {"shortest_edge": 20}						)
									self.assertEqual(image_processor.crop_size   ,     {"height": 18, "width": 18}						)

									a__ :int						  =    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  _snake_case					(	self						:   List[Any]						)      ->Tuple:






									"""simple docstring"""






									pass




						def  _snake_case					(	self						:   int						)      ->List[Any]:






									"""simple docstring"""






									a__ :Any						  =    self.image_processing_class(**self.image_processor_dict						)
									# create random PIL images
									a__ :Any						  =    prepare_image_inputs(self.image_processor_tester   ,     equal_resolution=__A						)
									for image in image_inputs:
												self.assertIsInstance(__A   ,     Image.Image						)

									# Test not batched input
									a__ :str						  =    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__ :str						  =    image_processing(__A   ,     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  _snake_case					(	self						:   List[Any]						)      ->str:






									"""simple docstring"""






									a__ :Union[str, Any]						  =    self.image_processing_class(**self.image_processor_dict						)
									# create random numpy tensors
									a__ :Dict						  =    prepare_image_inputs(self.image_processor_tester   ,     equal_resolution=__A   ,     numpify=__A						)
									for image in image_inputs:
												self.assertIsInstance(__A   ,     np.ndarray						)

									# Test not batched input
									a__ :Optional[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
									a__ :Any						  =    image_processing(__A   ,     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  _snake_case					(	self						:   Any						)      ->Dict:






									"""simple docstring"""






									a__ :str						  =    self.image_processing_class(**self.image_processor_dict						)
									# create random PyTorch tensors
									a__ :Union[str, Any]						  =    prepare_image_inputs(self.image_processor_tester   ,     equal_resolution=__A   ,     torchify=__A						)
									for image in image_inputs:
												self.assertIsInstance(__A   ,     torch.Tensor						)

									# Test not batched input
									a__ :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
									a__ :Optional[int]						  =    image_processing(__A   ,     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"],
									    )   ,     )






import datasets

from .evaluate import evaluate


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

snake_case__			 =						'''
This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.
'''

snake_case__			 =						'''
Computes SQuAD scores (F1 and EM).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - \'id\': id of the question-answer pair as given in the references (see below)
        - \'prediction_text\': the text of the answer
    references: List of question-answers dictionaries with the following key-values:
        - \'id\': id of the question-answer pair (see above),
        - \'answers\': a Dict in the SQuAD dataset format
            {
                \'text\': list of possible texts for the answer, as a list of strings
                \'answer_start\': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
Examples:

    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> squad_metric = datasets.load_metric("squad")
    >>> results = squad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact_match\': 100.0, \'f1\': 100.0}
'''


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




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






									"""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  _snake_case					(	self						:   Dict   ,     __A						:   List[Any]   ,     __A						:   Optional[int]						)      ->str:






									"""simple docstring"""






									a__ :Optional[int]						  =    {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
									a__ :Optional[Any]						  =    [
									    {
									        "paragraphs": [
									            {
									                "qas": [
									                    {
									                        "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
									                        "id": ref["id"],
									                    }
									                    for ref in references
									                ]
									            }
									        ]
									    }
									]
									a__ :Union[str, Any]						  =    evaluate(dataset=__A   ,     predictions=__A						)
									return score


