




'''simple docstring'''


import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


lowerCAmelCase_			:     Union[str, Any]							    =     "\\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_			:     Optional[int]							    =     "\nThis metric wrap the official scoring script for version 2 of the Stanford Question\nAnswering 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\nSQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions\nwritten adversarially by crowdworkers to look similar to answerable ones.\nTo do well on SQuAD2.0, systems must not only answer questions when possible, but also\ndetermine when no answer is supported by the paragraph and abstain from answering.\n"

lowerCAmelCase_			:     Optional[Any]							    =     "\nComputes SQuAD v2 scores (F1 and EM).\nArgs:\n    predictions: List of triple for question-answers to score with the following elements:\n        - the question-answer 'id' field as given in the references (see below)\n        - the text of the answer\n        - the probability that the question has no 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 list of Dict {'text': text of the answer as a string}\n    no_answer_threshold: float\n        Probability threshold to decide that a question has no answer.\nReturns:\n    'exact': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\n    'total': Number of score considered\n    'HasAns_exact': Exact match (the normalized answer exactly match the gold answer)\n    'HasAns_f1': The F-score of predicted tokens versus the gold answer\n    'HasAns_total': Number of score considered\n    'NoAns_exact': Exact match (the normalized answer exactly match the gold answer)\n    'NoAns_f1': The F-score of predicted tokens versus the gold answer\n    'NoAns_total': Number of score considered\n    'best_exact': Best exact match (with varying threshold)\n    'best_exact_thresh': No-answer probability threshold associated to the best exact match\n    'best_f1': Best F1 (with varying threshold)\n    'best_f1_thresh': No-answer probability threshold associated to the best F1\nExamples:\n\n    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22', 'no_answer_probability': 0.}]\n    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n    >>> squad_v2_metric = datasets.load_metric(\"squad_v2\")\n    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact': 100.0, 'f1': 100.0, 'total': 1, 'HasAns_exact': 100.0, 'HasAns_f1': 100.0, 'HasAns_total': 1, 'best_exact': 100.0, 'best_exact_thresh': 0.0, 'best_f1': 100.0, 'best_f1_thresh': 0.0}\n"







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






      def        lowercase_	(   self      :     Optional[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"""					),
                           """no_answer_probability""": datasets.Value("""float32"""					),
                       },
                       """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      :     List[Any]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Any	,	lowercase__      :     str=1.0					):


           '''simple docstring'''

           a_    :       Any    	=     {p['''id''']: p['''no_answer_probability'''] for p in predictions}
           a_    :       Tuple    	=     [{'''paragraphs''': [{'''qas''': references}]}]
           a_    :       List[Any]    	=     {p['''id''']: p['''prediction_text'''] for p in predictions}

           a_    :       Any    	=     make_qid_to_has_ans(__UpperCamelCase					)  # maps qid to True/False
           a_    :       List[Any]    	=     [k for k, v in qid_to_has_ans.items() if v]
           a_    :       Tuple    	=     [k for k, v in qid_to_has_ans.items() if not v]

           a_    :       Optional[Any]    	=     get_raw_scores(__UpperCamelCase	,	__UpperCamelCase					)
           a_    :       Tuple    	=     apply_no_ans_threshold(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase					)
           a_    :       Dict    	=     apply_no_ans_threshold(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase					)
           a_    :       int    	=     make_eval_dict(__UpperCamelCase	,	__UpperCamelCase					)

           if has_ans_qids:
                a_    :       str    	=     make_eval_dict(__UpperCamelCase	,	__UpperCamelCase	,	qid_list=__UpperCamelCase					)
                merge_eval(__UpperCamelCase	,	__UpperCamelCase	,	"""HasAns"""					)
           if no_ans_qids:
                a_    :       str    	=     make_eval_dict(__UpperCamelCase	,	__UpperCamelCase	,	qid_list=__UpperCamelCase					)
                merge_eval(__UpperCamelCase	,	__UpperCamelCase	,	"""NoAns"""					)
           find_all_best_thresh(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase					)
           return dict(__UpperCamelCase					)






'''simple docstring'''


import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import EfficientNetForImageClassification, EfficientNetModel
 from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Dict	,	lowercase__      :     Any	,	lowercase__      :     Tuple=13	,	lowercase__      :     Any=32	,	lowercase__      :     List[str]=3	,	lowercase__      :     Any=[3, 3, 5]	,	lowercase__      :     int=[32, 16, 24]	,	lowercase__      :     str=[16, 24, 40]	,	lowercase__      :     Optional[Any]=[1, 1, 2]	,	lowercase__      :     int=[1, 1, 2]	,	lowercase__      :     Tuple=[1, 6, 6]	,	lowercase__      :     Optional[Any]=True	,	lowercase__      :     Union[str, Any]=True	,	lowercase__      :     List[str]=37	,	lowercase__      :     Optional[int]="gelu"	,	lowercase__      :     str=10	,	):


           '''simple docstring'''

           a_    :       Dict    	=     parent
           a_    :       Any    	=     batch_size
           a_    :       str    	=     image_size
           a_    :       Tuple    	=     num_channels
           a_    :       Dict    	=     kernel_sizes
           a_    :       List[Any]    	=     in_channels
           a_    :       int    	=     out_channels
           a_    :       Union[str, Any]    	=     strides
           a_    :       List[Any]    	=     num_block_repeats
           a_    :       List[Any]    	=     expand_ratios
           a_    :       Dict    	=     is_training
           a_    :       Optional[int]    	=     hidden_act
           a_    :       List[Any]    	=     num_labels
           a_    :       List[str]    	=     use_labels






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           a_    :       List[Any]    	=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

           a_    :       int    	=     None
           if self.use_labels:
                a_    :       int    	=     ids_tensor([self.batch_size]	,	self.num_labels					)

           a_    :       List[Any]    	=     self.get_config()
           return config, pixel_values, labels






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           return EfficientNetConfig(
               num_channels=self.num_channels	,	kernel_sizes=self.kernel_sizes	,	in_channels=self.in_channels	,	out_channels=self.out_channels	,	strides=self.strides	,	num_block_repeats=self.num_block_repeats	,	expand_ratios=self.expand_ratios	,	hidden_act=self.hidden_act	,	num_labels=self.num_labels	,	)






      def        lowercase_	(   self      :     int	,	lowercase__      :     Any	,	lowercase__      :     Any	,	lowercase__      :     Optional[int]					):


           '''simple docstring'''

           a_    :       Tuple    	=     EfficientNetModel(config=lowercase__					)
           model.to(lowercase__					)
           model.eval()
           a_    :       Optional[int]    	=     model(lowercase__					)
           # expected last hidden states: B, C, H // 4, W // 4
           self.parent.assertEqual(
               result.last_hidden_state.shape	,	(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)	,	)






      def        lowercase_	(   self      :     Optional[Any]	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Any	,	lowercase__      :     str					):


           '''simple docstring'''

           a_    :       Dict    	=     EfficientNetForImageClassification(lowercase__					)
           model.to(lowercase__					)
           model.eval()
           a_    :       str    	=     model(lowercase__	,	labels=lowercase__					)
           self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels)					)






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           a_    :       Union[str, Any]    	=     self.prepare_config_and_inputs()
           a_	,    a_	,    a_    :       Optional[Any]    	=     config_and_inputs
           a_    :       str    	=     {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_torch
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					Any             =				(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
      __magic_name__     :					List[Any]             =				(
          {'''feature-extraction''': EfficientNetModel, '''image-classification''': EfficientNetForImageClassification}
          if is_torch_available()
          else {}
      )

      __magic_name__     :					int             =				False
      __magic_name__     :					Dict             =				False
      __magic_name__     :					Dict             =				False
      __magic_name__     :					Union[str, Any]             =				False
      __magic_name__     :					Optional[int]             =				False






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     EfficientNetModelTester(self					)
           a_    :       Union[str, Any]    	=     ConfigTester(
               self	,	config_class=lowercase__	,	has_text_modality=lowercase__	,	hidden_size=37					)






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           self.create_and_test_config_common_properties()
           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           return






      @unittest.skip(reason="""EfficientNet does not use inputs_embeds"""					)
      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""					)
      def        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""EfficientNet does not use feedforward chunking"""					)
      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           a_	,    a_    :       Dict    	=     self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_    :       Tuple    	=     model_class(lowercase__					)
                a_    :       int    	=     inspect.signature(model.forward					)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                a_    :       Any    	=     [*signature.parameters.keys()]

                a_    :       Dict    	=     ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]	,	lowercase__					)






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           a_    :       Tuple    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase__					)






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           def check_hidden_states_output(lowercase__      :     Optional[int]	,	lowercase__      :     List[Any]	,	lowercase__      :     Tuple					):
                a_    :       str    	=     model_class(lowercase__					)
                model.to(lowercase__					)
                model.eval()

                with torch.no_grad():
                     a_    :       Tuple    	=     model(**self._prepare_for_class(lowercase__	,	lowercase__					)					)

                a_    :       Tuple    	=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                a_    :       Tuple    	=     sum(config.num_block_repeats					) * 4
                self.assertEqual(len(lowercase__					)	,	lowercase__					)

                # EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
                self.assertListEqual(
                    list(hidden_states[0].shape[-2:]					)	,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2]	,	)

           a_	,    a_    :       Any    	=     self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_    :       Any    	=     True
                check_hidden_states_output(lowercase__	,	lowercase__	,	lowercase__					)

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                a_    :       Any    	=     True

                check_hidden_states_output(lowercase__	,	lowercase__	,	lowercase__					)






      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase__					)






      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""					)
      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           pass






      @slow
      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                a_    :       List[str]    	=     EfficientNetModel.from_pretrained(lowercase__					)
                self.assertIsNotNone(lowercase__					)






      @is_pipeline_test
      @require_vision
      @slow
      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           super().test_pipeline_image_classification()



def    _SCREAMING_SNAKE_CASE    (			):




     """simple docstring"""


     a_    :       List[str]    	=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
     return image







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      @cached_property
      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""					) if is_vision_available() else None






      @slow
      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""					).to(lowercase__					)

           a_    :       Any    	=     self.default_image_processor
           a_    :       List[str]    	=     prepare_img()
           a_    :       str    	=     image_processor(images=lowercase__	,	return_tensors="""pt"""					).to(lowercase__					)

           # forward pass
           with torch.no_grad():
                a_    :       Tuple    	=     model(**lowercase__					)

           # verify the logits
           a_    :       Dict    	=     torch.Size((1, 1000)					)
           self.assertEqual(outputs.logits.shape	,	lowercase__					)

           a_    :       List[Any]    	=     torch.tensor([0.0001, 0.0002, 0.0002]					).to(lowercase__					)
           self.assertTrue(torch.allclose(outputs.logits[0, :3]	,	lowercase__	,	atol=1e-4					)					)
