





import datasets

from .evaluate import evaluate


__A							:			int         =			"\\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"

__A							:			int         =			"\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"

__A							:			int         =			"\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      lowerCamelCase(						datasets.Metric	):
     '''simple docstring'''


     def        lowerCAmelCase__		(    self							):
         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        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_							):
         _A     =							{prediction['id']: prediction['prediction_text'] for prediction in predictions}
         _A     =							[
             {
                 'paragraphs': [
                     {
                         'qas': [
                             {
                                 'answers': [{'text': answer_text} for answer_text in ref['answers']['text']],
                                 'id': ref['id'],
                             }
                             for ref in references
                         ]
                     }
                 ]
             }
         ]
         _A     =							evaluate(dataset=snake_case_				,     predictions=snake_case_							)
         return score









"""simple docstring"""


import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


__snake_case    					=					get_tests_dir('fixtures')

class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							str:
    # A mock response for an HTTP head request to emulate server down
    lowercase__       :       List[str]				=						mock.Mock()
    lowercase__       :       Dict				=						500
    lowercase__       :       Any				=						{}
    lowercase__       :       int				=						HTTPError
    lowercase__       :       Optional[int]				=						{}

    # Download this model to make sure it's in the cache.
    lowercase__       :       Dict				=						ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit"""						)
    # Under the mock environment we get a 500 error when trying to reach the model.
    with mock.patch("""requests.Session.request""" ,     return_value=lowerCamelCase__						) as mock_head:
     lowercase__       :       Dict				=						ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit"""						)
     # This check we did call the fake head request
     mock_head.assert_called()


   def 					UpperCAmelCase__(						self						)      ->							Dict:
    # This test is for deprecated behavior and can be removed in v5
    lowercase__       :       Dict				=						ViTImageProcessor.from_pretrained(
        """https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json"""						)







   def 					UpperCAmelCase__(						self						)      ->							Tuple:
    with self.assertRaises(lowerCamelCase__						):
     # config is in subfolder, the following should not work without specifying the subfolder
     lowercase__       :       List[str]				=						AutoImageProcessor.from_pretrained("""hf-internal-testing/stable-diffusion-all-variants"""						)

    lowercase__       :       Any				=						AutoImageProcessor.from_pretrained(
        """hf-internal-testing/stable-diffusion-all-variants""" ,     subfolder="""feature_extractor"""						)

    self.assertIsNotNone(lowerCamelCase__						)

@is_staging_test
class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   @classmethod
   def 					UpperCAmelCase__(						cls						)      ->							int:
    lowercase__       :       str				=						TOKEN
    HfFolder.save_token(lowerCamelCase__						)


   @classmethod
   def 					UpperCAmelCase__(						cls						)      ->							List[str]:
    try:
     delete_repo(token=cls._token ,     repo_id="""test-image-processor"""						)
    except HTTPError:
     pass

    try:
     delete_repo(token=cls._token ,     repo_id="""valid_org/test-image-processor-org"""						)
    except HTTPError:
     pass

    try:
     delete_repo(token=cls._token ,     repo_id="""test-dynamic-image-processor"""						)
    except HTTPError:
     pass


   def 					UpperCAmelCase__(						self						)      ->							int:
    lowercase__       :       List[str]				=						ViTImageProcessor.from_pretrained(lowerCamelCase__						)
    image_processor.push_to_hub("""test-image-processor""" ,     use_auth_token=self._token						)

    lowercase__       :       str				=						ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)

    # Reset repo
    delete_repo(token=self._token ,     repo_id="""test-image-processor"""						)

    # Push to hub via save_pretrained
    with tempfile.TemporaryDirectory() as tmp_dir:
     image_processor.save_pretrained(
         lowerCamelCase__ ,     repo_id="""test-image-processor""" ,     push_to_hub=lowerCamelCase__ ,     use_auth_token=self._token						)

    lowercase__       :       Union[str, Any]				=						ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)


   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       Tuple				=						ViTImageProcessor.from_pretrained(lowerCamelCase__						)
    image_processor.push_to_hub("""valid_org/test-image-processor""" ,     use_auth_token=self._token						)

    lowercase__       :       Any				=						ViTImageProcessor.from_pretrained("""valid_org/test-image-processor"""						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)

    # Reset repo
    delete_repo(token=self._token ,     repo_id="""valid_org/test-image-processor"""						)

    # Push to hub via save_pretrained
    with tempfile.TemporaryDirectory() as tmp_dir:
     image_processor.save_pretrained(
         lowerCamelCase__ ,     repo_id="""valid_org/test-image-processor-org""" ,     push_to_hub=lowerCamelCase__ ,     use_auth_token=self._token						)

    lowercase__       :       List[Any]				=						ViTImageProcessor.from_pretrained("""valid_org/test-image-processor-org"""						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)







   def 					UpperCAmelCase__(						self						)      ->							Dict:
    CustomImageProcessor.register_for_auto_class()
    lowercase__       :       List[str]				=						CustomImageProcessor.from_pretrained(lowerCamelCase__						)

    image_processor.push_to_hub("""test-dynamic-image-processor""" ,     use_auth_token=self._token						)

    # This has added the proper auto_map field to the config
    self.assertDictEqual(
        image_processor.auto_map ,     {"""AutoImageProcessor""": """custom_image_processing.CustomImageProcessor"""} ,     )

    lowercase__       :       Dict				=						AutoImageProcessor.from_pretrained(
        F'''{USER}/test-dynamic-image-processor''' ,     trust_remote_code=lowerCamelCase__						)
    # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
    self.assertEqual(new_image_processor.__class__.__name__ ,     """CustomImageProcessor"""						)